Unity 协程实现依次到达多个目标点
在Unity中,可以通过协程实现依次到达多个目标点的功能。以下是一个示例代码:
using System.Collections;
using UnityEngine;
public class MoveToTargets : MonoBehaviour
{
public Transform[] targets; // 目标点数组
public float moveSpeed = 5f; // 移动速度
private int currentIndex = 0; // 当前目标点索引
private void Start()
{
StartCoroutine(MoveToNextTarget());
}
private IEnumerator MoveToNextTarget()
{
while (currentIndex < targets.Length)
{
// 获取当前目标点的位置
Vector3 targetPosition = targets[currentIndex].position;
// 计算移动方向和距离
Vector3 direction = (targetPosition - transform.position).normalized;
float distance = Vector3.Distance(transform.position, targetPosition);
// 移动到目标点
while (distance > 0.1f)
{
transform.position += direction * moveSpeed * Time.deltaTime;
distance = Vector3.Distance(transform.position, targetPosition);
yield return null;
}
// 到达目标点后,等待一段时间
yield return new WaitForSeconds(1f);
// 移动到下一个目标点
currentIndex++;
}
}
}
在上述代码中,我们首先定义了一个targets数组,用于存储所有的目标点(可以在Unity编辑器中手动指定)。然后在Start方法中启动一个协程MoveToNextTarget。
MoveToNextTarget协程中,通过一个while循环遍历所有的目标点。在每个目标点上,我们计算出移动方向和距离,并通过一个内部的while循环实现平滑移动。当到达目标点后,我们使用yield return new WaitForSeconds(1f)等待1秒钟,然后移动到下一个目标点。
这样,物体就可以依次到达每个目标点了。
原文地址: https://www.cveoy.top/t/topic/1qB 著作权归作者所有。请勿转载和采集!