Unity 实现按照设定路线行走脚本与操作

这个代码是从官网的一个Demo中扒出来的,Demo中代码较多,好多用不到,不利于查看核心代码

核心代码

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor;
#endif


public class WaypointCircuit : MonoBehaviour {

    public WaypointList waypointList = new WaypointList();
    [SerializeField] bool smoothRoute = true;
    int numPoints;
    Vector3[] points;
    float[] distances;

    public float editorVisualisationSubsteps = 100;
    public float Length { get; private set; }
    public Transform[] Waypoints { get { return waypointList.items; } }

    //this being here will save GC allocs
    int p0n;
    int p1n;
    int p2n;
    int p3n;

    private float i;
    Vector3 P0;
    Vector3 P1;
    Vector3 P2;
    Vector3 P3;

    // Use this for initialization
    void Awake () {
        if (Waypoints.Length > 1)
        {
            CachePositionsAndDistances();
        }
        numPoints = Waypoints.Length;
    }

    public RoutePoint GetRoutePoint(float dist)
    {
        // position and direction
        Vector3 p1 = GetRoutePosition(dist);
        Vector3 p2 = GetRoutePosition(dist + 0.1f);
        Vector3 delta = p2-p1;
        return new RoutePoint( p1, delta.normalized );
    }

    public Vector3 GetRoutePosition(float dist)
    {
        int point = 0;

        if (Length == 0)
        {
            Length = distances[distances.Length-1];
        }

        dist = Mathf.Repeat(dist,Length);

        while (distances[point] < dist) { ++point; }


        // get nearest two points, ensuring points wrap-around start & end of circuit
        p1n = ((point-1) + numPoints) % numPoints;
        p2n = point;

        // found point numbers, now find interpolation value between the two middle points

        i = Mathf.InverseLerp(distances[p1n],distances[p2n],dist);

        if (smoothRoute)
        {
            // smooth catmull-rom calculation between the two relevant points



            // get indices for the surrounding 2 points, because
            // four points are required by the catmull-rom function
            p0n = ((point-2) + numPoints) % numPoints;
            p3n = (point+1) % numPoints;

            // 2nd point may have been the 'last' point - a dupe of the first,
            // (to give a value of max track distance instead of zero)
            // but now it must be wrapped back to zero if that was the case.
            p2n = p2n % numPoints;

            P0 = points[ p0n ];
            P1 = points[ p1n ];
            P2 = points[ p2n ];
            P3 = points[ p3n ];

            return CatmullRom(P0,P1,P2,P3,i);

        } else {

            // simple linear lerp between the two points:

            p1n = ((point-1) + numPoints) % numPoints;
            p2n = point;

            return Vector3.Lerp ( points[p1n], points[p2n], i );

        }

    }



    Vector3 CatmullRom(Vector3 _P0, Vector3 _P1, Vector3 _P2, Vector3 _P3, float _i)
    {
        // comments are no use here... it's the catmull-rom equation.
        // Un-magic this, lord vector!
        return 0.5f * ( (2 * _P1) + (-_P0 + _P2) * _i + (2*_P0 - 5*_P1 + 4*_P2 - _P3) * _i*_i + (-_P0 + 3*_P1 - 3*_P2 + _P3) * _i*_i*_i );
    }


    void CachePositionsAndDistances()
    {
        // transfer the position of each point and distances between points to arrays for
        // speed of lookup at runtime
        points = new Vector3[Waypoints.Length+1];
        distances = new float[Waypoints.Length+1];

        float accumulateDistance = 0;
        for (int i = 0; i<points.Length; ++i) {
            var t1 =  Waypoints[(i)% Waypoints.Length ];
            var t2 =  Waypoints[(i+1)% Waypoints.Length ];
            if (t1 != null && t2 != null)
            {
                Vector3 p1 = t1.position;
                Vector3 p2 = t2.position;
                points[i] = Waypoints[i % Waypoints.Length].position;
                distances[i] = accumulateDistance;
                accumulateDistance += (p1 - p2).magnitude;
            } 
        }
    }


    void OnDrawGizmos()
    {
        DrawGizmos(false);
    }

    void OnDrawGizmosSelected()
    {
        DrawGizmos(true);
    }

    void DrawGizmos(bool selected)
    {
        waypointList.circuit = this;
        if (Waypoints.Length > 1)
        {
            numPoints = Waypoints.Length;

            CachePositionsAndDistances();
            Length = distances[distances.Length-1];

            Gizmos.color = selected ? Color.yellow : new Color(1,1,0,0.5f);
            Vector3 prev = Waypoints[0].position;
            if (smoothRoute)
            {
                for (float dist=0; dist<Length; dist += Length/editorVisualisationSubsteps)
                {
                    Vector3 next = GetRoutePosition(dist+1);
                    Gizmos.DrawLine( prev, next );
                    prev = next;
                }
                Gizmos.DrawLine( prev, Waypoints[0].position );
            } else {

                for (int n=0; n<Waypoints.Length; ++n)
                {
                    Vector3 next = Waypoints[(n+1) % Waypoints.Length].position;
                    Gizmos.DrawLine( prev, next );
                    prev = next;
                }
            }
        }
    }

    [System.Serializable]
    public class WaypointList
    {
        public WaypointCircuit circuit;
        public Transform[] items = new Transform[0];
    }

    public struct RoutePoint
    {
        public Vector3 position;
        public Vector3 direction;

        public RoutePoint(Vector3 position, Vector3 direction)
        {
            this.position = position;
            this.direction = direction;
        }

    }


}



#if UNITY_EDITOR
[CustomPropertyDrawer (typeof(WaypointCircuit.WaypointList))]
public class WaypointListDrawer : PropertyDrawer
{
    float lineHeight = 18;
    float spacing = 4;

    public override void OnGUI (Rect position, SerializedProperty property, GUIContent label)
    {
        EditorGUI.BeginProperty (position, label, property);

        float x = position.x;
        float y = position.y;
        float inspectorWidth = position.width;

        // Draw label


        // Don't make child fields be indented
        var indent = EditorGUI.indentLevel;
        EditorGUI.indentLevel = 0;

        var items = property.FindPropertyRelative ("items");
        string[] titles = new string[] { "Transform", "", "", "" };
        string[] props = new string[] { "transform", "^", "v", "-" };
        float[] widths = new float[] { .7f, .1f, .1f, .1f };
        float lineHeight = 18;
        bool changedLength = false;
        if (items.arraySize > 0)
        {

            for (int i=-1; i<items.arraySize; ++i) {

                var item = items.GetArrayElementAtIndex (i);

                float rowX = x;
                for (int n=0; n<props.Length; ++n)
                {
                    float w = widths[n] * inspectorWidth;

                    // Calculate rects
                    Rect rect = new Rect (rowX, y, w, lineHeight);
                    rowX += w;

                    if (i == -1)
                    {
                        EditorGUI.LabelField(rect, titles[n]);
                    } else {
                        if (n==0)
                        {
                            EditorGUI.ObjectField(rect, item.objectReferenceValue, typeof(Transform), true);                        
                        } else {
                            if (GUI.Button (rect, props[n]))
                            {
                                switch (props[n])
                                {
                                case "-":
                                    items.DeleteArrayElementAtIndex(i);
                                    items.DeleteArrayElementAtIndex(i);
                                    changedLength = true;
                                    break;
                                case "v":
                                    if (i > 0) items.MoveArrayElement(i,i+1);
                                    break;
                                case "^":
                                    if (i < items.arraySize-1) items.MoveArrayElement(i,i-1);
                                    break;
                                }

                            }
                        }
                    }
                }

                y += lineHeight + spacing;
                if (changedLength)
                {
                    break;
                }
            }

        } else {

            // add button
            var addButtonRect = new Rect ((x + position.width) - widths[widths.Length-1]*inspectorWidth, y, widths[widths.Length-1]*inspectorWidth, lineHeight);
            if (GUI.Button (addButtonRect, "+")) {
                items.InsertArrayElementAtIndex(items.arraySize);
            }

            y += lineHeight + spacing;
        }

        // add all button
        var addAllButtonRect = new Rect (x, y, inspectorWidth, lineHeight);
        if (GUI.Button (addAllButtonRect, "Assign using all child objects"))
        {
            var circuit = property.FindPropertyRelative("circuit").objectReferenceValue as WaypointCircuit;
            var children = new Transform[ circuit.transform.childCount ];
            int n=0; foreach (Transform child in circuit.transform) children[n++] = child;
            System.Array.Sort( children, new TransformNameComparer() );
            circuit.waypointList.items = new Transform[children.Length];
            for (n=0; n<children.Length; ++n)
            {
                circuit.waypointList.items[n] = children[n];
            }


        }
        y += lineHeight + spacing;

        // rename all button
        var renameButtonRect = new Rect (x, y, inspectorWidth, lineHeight);
        if (GUI.Button (renameButtonRect, "Auto Rename numerically from this order")) {
            var circuit = property.FindPropertyRelative("circuit").objectReferenceValue as WaypointCircuit;
            int n=0; foreach (Transform child in circuit.waypointList.items) child.name = "Waypoint "+(n++).ToString("000");

        }
        y += lineHeight + spacing;

        // Set indent back to what it was
        EditorGUI.indentLevel = indent;
        EditorGUI.EndProperty ();
    }

    public override float GetPropertyHeight (SerializedProperty property, GUIContent label)
    {
        SerializedProperty items = property.FindPropertyRelative ("items");
        float lineAndSpace = lineHeight + spacing;
        return 40 + (items.arraySize * lineAndSpace) + lineAndSpace;
    }

    // comparer for check distances in ray cast hits
    public class TransformNameComparer: IComparer
    {
        public int Compare(object x, object y) {
            return ((Transform)x).name.CompareTo(((Transform)y).name);
        }   
    }

}
#endif

(1)新建一个Unity 工程,将上面代码复制到脚本中

(2)创建一个空的GameObject,在GameObject下创建四个Cube,作为 4 个路点。

Paste_Image.png

将 WaypointCircuit.cs 脚本拖拽到 GameObject上
点击 Assign using all child objects 按钮

Paste_Image.png

自动将GameObject 的子对象添加到路点

Paste_Image.png

点击 Auto Rename numerically from this order 按钮,将自动修改 GameObject子物体的名字,并且在Scene下绘制出路径
(3)使用路径,新建一个 Sphere作为移动物体,创建一个 脚本 Follow.cs

using UnityEngine;
using System.Collections;

public class Follow : MonoBehaviour {

    // 路径脚本
    [SerializeField]
    private WaypointCircuit circuit;

    //移动距离
    private float dis;
    //移动速度
    private float speed;
    // Use this for initialization
    void Start()
    {
        dis = 0;
        speed = 10;
    }

    // Update is called once per frame
    void Update()
    {
        //计算距离
        dis += Time.deltaTime * speed;
        //获取相应距离在路径上的位置坐标
        transform.position = circuit.GetRoutePoint(dis).position;
        //获取相应距离在路径上的方向
        transform.rotation = Quaternion.LookRotation(circuit.GetRoutePoint(dis).direction);
    }
}

将 Follow.cs 脚本拖拽到 Sphere 上,将GameObject 拖拽到 Circuit 参数上

Paste_Image.png

Paste_Image.png

(4)运行项目,Sphere在路径上完美行走

Paste_Image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,658评论 6 496
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,482评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,213评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,395评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,487评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,523评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,525评论 3 414
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,300评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,753评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,048评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,223评论 1 343
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,905评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,541评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,168评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,417评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,094评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,088评论 2 352

推荐阅读更多精彩内容

  • 一、Unity简介 1. Unity界面 Shift + Space : 放大界面 Scene界面按钮渲染模式2D...
    MYves阅读 8,191评论 0 22
  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 12,710评论 2 59
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,979评论 25 707
  • This article is a record of my journey to learn Game Deve...
    蔡子聪阅读 3,774评论 0 9
  • 从废墟之中爬起 淋漓鲜血,硝烟碎石 我向着永恒开战 你是我不倒的旗帜 人生,惨淡而苟且 我却想成为勇士 浴血奋战,...
    作家明至阅读 178评论 0 3