找回密码
 立即注册
查看: 209|回复: 0

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

[复制链接]
发表于 2023-3-7 16:04 | 显示全部楼层 |阅读模式
已经存在一个用于保存所有路径点的列表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,以便对象可以从头开始循环移动。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Unity开发者联盟 ( 粤ICP备20003399号 )

GMT+8, 2024-6-17 07:43 , Processed in 0.087646 second(s), 26 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表