在 Unity 中,可以使用协程来实现多点寻路功能。下面是一个简单的例子,演示了如何通过协程来依次移动物体到多个指定的目标点。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Pathfinding : MonoBehaviour
{
    public Transform[] waypoints; // 目标点数组
    public float moveSpeed = 5f; // 移动速度

    private int currentWaypoint = 0; // 当前目标点索引

    private void Start()
    {
        StartCoroutine(FollowPath()); // 启动协程
    }

    private IEnumerator FollowPath()
    {
        while (currentWaypoint < waypoints.Length)
        {
            Vector3 targetPosition = waypoints[currentWaypoint].position; // 获取当前目标点的位置

            while (transform.position != targetPosition)
            {
                // 移动物体向目标点靠近
                transform.position = Vector3.MoveTowards(transform.position, targetPosition, moveSpeed * Time.deltaTime);
                yield return null;
            }

            // 到达目标点后,将当前目标点索引递增
            currentWaypoint++;
        }
    }
}

在上述代码中,首先定义了一个waypoints数组,用于存储多个目标点的Transform组件。然后,在Start方法中启动了一个协程FollowPath。在FollowPath协程中,使用一个while循环来遍历每个目标点。在每一次循环中,使用Vector3.MoveTowards方法来逐渐移动物体向目标点靠近。当物体到达目标点后,递增currentWaypoint索引,继续移动到下一个目标点。通过不断地循环,直到所有目标点都到达完成寻路。

可以将上述代码添加到一个空物体上,并在Inspector面板中设置waypoints数组的元素为需要寻路的目标点。

Unity 协程实现多点寻路:代码示例与解析

原文地址: https://www.cveoy.top/t/topic/1uX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录