我正在做一个RTS项目,我想用Aron Granberg的A *项目来解决障碍。 问题是在场景中显示正确的path,单位仍然向前走,但单位跳到(0,0,0)。 现在,这是一个解决方法,在我的构建脚本中取得了一些进展。
为什么我的A *对象重置为(0,0,0),而不是跟随其path?
我不知道我犯了什么错误导致了这种行为。 这里是负责运动的脚本:
using UnityEngine; using Pathfinding; using RTS; public class Unit : WorldObject { public float moveSpeed; public Path path; public float nextWaypointDistance = 3; private int currentWaypoint = 0; protected override void Update() { Vector3 dir = (path.vectorPath[currentWaypoint] - transform.position).normalized; MakeMove(dir); if (Vector3.Distance(transform.position, path.vectorPath[currentWaypoint]) < nextWaypointDistance) { currentWaypoint++; return; } } private void MakeMove(Vector3 dir) { transform.position = Vector3.MoveTowards(transform.position, dir, Time.deltaTime * moveSpeed); } }
你的问题是你提供一个规范化的方向作为Vector3.MoveTowards()
的第二个参数,其中第二个参数被假设为目标坐标。 正如你已经发现的,提供目标而不是方向可以解决你的问题。
我们来看看API资源 。
Vector3.MoveTowards
public static Vector3 MoveTowards (Vector3 current ,Vector3 target ,float maxDistanceDelta );
…描述
将点电stream以直线移动到目标点。
这个函数返回的值是一个点,
maxDistanceDelta
单位更接近一个目标/点沿着current
和target
之间的一条线。
…
– Unity API:Vector3.MoveTowards
问题被发现:
改变Vector3 dir = (path.vectorPath[currentWaypoint] - transform.position).normalized;
到Vector3 dir = path.vectorPath[currentWaypoint] worked.
但是我仍然不知道为什么。