using UnityEngine;
using System.Collections;
/// <summary>
/// 脚本功能:自动寻路功能
/// 脚本位置:移动的主角身上
/// </summary>
public class WayPoint : MonoBehaviour
{
// 每个路点设置为Trigger。
// 移动主角添加Rigibody属性。
// 这里使用了拖拽方式,如果路点的名字是带有数字,并且连续的,可以使用for循环代码加载
public Transform[] WayPoints;
// 移动速度
private float MoveSpeed = 3f;
// 当前人物需要移动的方向向量
Vector3 direction;
// 下一个路点的索引
private int nextIndex;
void Start ()
{
nextIndex = 0;
}
void Update ()
{
// 通过向量减法,算出朝向下一个路点的方向向量
direction = (WayPoints [nextIndex].position - transform.position).normalized;
transform.Translate(direction * MoveSpeed * Time.deltaTime);
}
void OnTriggerEnter (Collider other)
{
nextIndex++;
Debug.Log (nextIndex);
// 这里我使用了4个路点,会循环,所以每次到最后一个点就会回到起点
// 大家可以根据自己的需求更改代码
if (nextIndex >= 4) {
nextIndex = 0;
}
}
}
【Unity】中WayPoint路点的配置
最新推荐文章于 2024-01-23 11:10:54 发布