您的位置:首页 > 移动开发 > Unity3D

Unity中WayPoint路点的配置

2015-09-23 17:43 429 查看
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; 
		}
 
	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: