我正在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);
1条答案
按热度按时间camsedfj1#
根据描述-并且知道
Vector2.MoveTowards
本身工作正常-听起来更像是对象实际上正确移动了。仍在3D空间中进行比较,因此还考虑了在
Vector2.MoveTowards
中被忽略/擦除的Z轴=〉如果您的
targetPosition
包含任何z != 0
,您的检查将永远失败。我想如果您也停止比较3D矢量,而是这样做,它将正常工作