unity中如何让一个对象沿着路径点循环移动

已经存在一个用于保存所有路径点的列表public List<Vector3> List_PathPoint = new List<Vector3>();,要让对象沿着列表的点按照MoveSpeed的速度循环移动, 可以使用一个指针来指示当前应该移动到的路径点的索引,然后在Update函数中通过Vector3.MoveTowards方法将对象移动到下一个路径点。当对象到达列表中的最后一个路径点时,将指针重置为0,以便对象可以从头开始循环移动。

public List<Vector3> List_PathPoint = new List<Vector3>();
public float MoveSpeed = 5f;

private int currentPathIndex = 0;

void Update()
{
// 获取当前指向的路径点
Vector3 currentTarget = List_PathPoint[currentPathIndex];

// 计算移动方向和距离
Vector3 moveDirection = currentTarget - transform.position;
float distanceToTarget = moveDirection.magnitude;

// 如果距离小于可以接受的误差,则移动到下一个路径点
if (distanceToTarget < 0.1f)
{
currentPathIndex++;
if (currentPathIndex >= List_PathPoint.Count)
{
currentPathIndex = 0;
}
}
else
{
// 向下一个路径点移动
Vector3 moveVector = moveDirection.normalized * MoveSpeed * Time.deltaTime;
transform.position += moveVector;
}
}


在此示例中,每帧都会计算对象当前应该移动到的路径点,并将其向该点移动。如果对象到达路径点,则将指针移动到下一个路径点。当对象到达列表中的最后一个路径点时,指针将重置为0,以便对象可以从头开始循环移动。

5be4ecb2fd00bc63528e131f1cea300b.jpeg

猜你喜欢

转载自blog.csdn.net/shguxudong11/article/details/129364806