Vector3.MoveTowards工作正常,但Vector2.MoveTowards在Unity3d中不工作

ehxuflar  于 2023-02-05  发布在  其他
关注(0)|答案(1)|浏览(162)

我正在UNITY的2D环境中使用航点构建敌人路径
使用Unity 2021.3将EnemyPathing.CS附加到敌人预置

public class EnemyPathing : MonoBehaviour 
{ 
    [SerializeField] List<Transform> waypoints; 
    [SerializeField] float moveSpeed = 2f; int waypointIndex = 0;
    // Start is called before the first frame update
    void Start()
    {
        transform.position = waypoints[waypointIndex].transform.position;
    }
    
    // Update is called once per frame
    void Update()
    {
        Move();
    }
    
    private void Move()
    {
        if (waypointIndex <= waypoints.Count - 1)
        {
            var targetPosition = waypoints[waypointIndex].transform.position;
            var movementThisFrame = moveSpeed * Time.deltaTime;

            // Issue here
            transform.position = Vector2.MoveTowards(transform.position, targetPosition, movementThisFrame);

            if (transform.position == targetPosition)
            {
                waypointIndex++;
            }
        }
        else
        {
            Destroy(gameObject);
        }
    }
}

当我使用Vector2MoveTowards时,敌人卡住了waypointIndex[0],无法移动下一个航点

transform.position = Vector2.MoveTowards(transform.position, targetPosition, movementThisFrame);

Vector3.MoveTowards工作正常,因为它应该是我的问题是为什么Vector2.MoveTowards不工作

transform.position = Vector3.MoveTowards(transform.position, targetPosition, movementThisFrame);
camsedfj

camsedfj1#

根据描述-并且知道Vector2.MoveTowards本身工作正常-听起来更像是对象实际上正确移动了。

if(transform.position == targetPosition)

仍在3D空间中进行比较,因此还考虑了在Vector2.MoveTowards中被忽略/擦除的Z轴
=〉如果您的targetPosition包含任何z != 0,您的检查将永远失败。
我想如果您也停止比较3D矢量,而是这样做,它将正常工作

if((Vector2)transform.position == (Vector2)targetPosition)

相关问题