Unity----WayPoint寻路

来源:互联网 发布:安卓软件编写 编辑:程序博客网 时间:2024/06/14 13:27
using UnityEngine;using System.Collections;public class WayPointAI : MonoBehaviour {    public Path path;    private Vector3 pos;    private float rotateSpeed = 10f;    private float moveSpeed = 5f;    // Use this for initialization    void Start()    {        if (path != null && path.HasNextPoint())        {            pos = path.GetNextPoint();        }    }    // Update is called once per frame    void Update()    {        bool reached = MoveToTarget(pos);        if (reached == true && path != null && path.HasNextPoint())        {            pos = path.GetNextPoint();        }    }    bool MoveToTarget(Vector3 point)    {        //只在XZ平面上移动,消除鼠标点击对Y轴的偏移,保持transform.y        //  Vector3 pointR = new Vector3(point.x, transform.position.y, point.z);        Vector3 pointR = new Vector3(point.x, point.y, point.z);        //Quaternion插值 物体朝向目标点平缓转向        Quaternion wantedRot = Quaternion.LookRotation(pointR - transform.position);        transform.rotation = Quaternion.Lerp(transform.rotation, wantedRot, rotateSpeed * Time.deltaTime);        //使用插值当物体到达目标点以后,会有抖动现象,在point处消除抖动        float distance = Vector3.Distance(pointR, transform.position);        if (distance < 0.05f)        {            return true;    //到达point        }        //向目标点移动        Vector3 direction = (pointR - transform.position).normalized;        transform.Translate(direction * moveSpeed * Time.deltaTime, Space.World);        return false;    }}




using UnityEngine;using System.Collections;public class Path : MonoBehaviour {    public Transform[] wayPoints;    public ArrayList points;   //存储wayPoints的transform.position属性    // Use this for initialization    void Awake()    {        //print("path");        points = new ArrayList();        for (int i = 0; i < wayPoints.Length; i++)        {            points.Add(wayPoints[i].transform.position);        }    }    //判断是否有下一个路径点    public bool HasNextPoint()    {        //points实例化过,并且存在N个路径点        if (points != null && points.Count > 0)        {            return true;        }        return false;    }    public Vector3 GetNextPoint()    {        if (points != null && points.Count > 0)        {            Vector3 p = (Vector3)points[0];            points.RemoveAt(0);            return p;        }        return Vector3.zero;    }    void OnDrawGizmos()    {        if (wayPoints.Length > 0)        {            iTween.DrawPath(wayPoints, Color.white);        }    }}

http://www.cnblogs.com/greyhh/p/4713256.html

0 0