Unity 物体运动 之 物体按规定路线运动的使用

 时间:2026-04-22 09:52:56

1、Transform.Translate:

1)功能简述

public void Translate(Vector3 translation, Space relativeTo = Space.Self);

Moves the transform in the direction and distance of translation.

If relativeTo is left out or set to Space.Self the movement is applied relative to the transform's local axes. (the x, y and z axes shown when selecting the object inside the Scene View.) If relativeTo is Space.World the movement is applied relative to the world coordinate system.

2)使用举例

 using UnityEngine;

 using System.Collections;public class ExampleClass : MonoBehaviour {

    void Update() {

        transform.Translate(Vector3.forward * Time.deltaTime);

        transform.Translate(Vector3.up * Time.deltaTime, Space.World);

    }

 }

1、打开Unity,新建一个工程,具体如下图

Unity 物体运动 之 物体按规定路线运动的使用

2、在场景中,新建一个“Plane”和“Cube”,合理调整他们的大小与布局,具体如下图

Unity 物体运动 之 物体按规定路线运动的使用

3、在场景中,新建2个“GameObject”作为路线点,把子类的设置标签,然后重复复制几个并调整位置,具体如下图

Unity 物体运动 之 物体按规定路线运动的使用

Unity 物体运动 之 物体按规定路线运动的使用

4、在工程中新建2个脚本,分别是“Move”“WayPoints”,双击脚本或者右键“Open C# Peoject”打开脚本,具体如下图

Unity 物体运动 之 物体按规定路线运动的使用

5、在“WayPoints”进行代码编辑,具体代码和代码说明如下图

Unity 物体运动 之 物体按规定路线运动的使用

6、“WayPoints”具体人内容如下:

using UnityEngine;

public class WayPoints : MonoBehaviour {

    public static Transform[] wayPoints;

    void Awake () {

        int count = transform.childCount;

        wayPoints = new Transform[count];

        for(int i = 0; i < count; i ++) {

            wayPoints [i] = transform.GetChild (i);

        }

    }

}

7、在“Move”进行代码编辑,具体代码和代码说明如下图

Unity 物体运动 之 物体按规定路线运动的使用

8、“Move”具体人内容如下:

using UnityEngine;

public class Move : MonoBehaviour {

    public float speed = 5;

    private Transform[] ways;

    private int index ;

    // Use this for initialization

    void Start () {

        ways = WayPoints.wayPoints;

        index = 0;

    }

        // Update is called once per frame

    void Update () {

        MoveTo ();

    }

    void MoveTo() {

        if (index > ways.Length-1) {

            return;

        }

        transform.Translate ((ways[index].position - 

            transform.position).normalized * Time.deltaTime * speed);

                if(Vector3.Distance(ways[index].position,transform.position) < 0.2f){

            index ++;

            if(index == ways.Length){

                transform.position = ways[index -1].position;

            }

        }

    }

}

9、脚本编译正确,回到Unity界面,把“Move”脚本赋给场景中的“Cube”,把脚本“WayPoints”赋给场景中的“WayPoints”,具体如下图

Unity 物体运动 之 物体按规定路线运动的使用

Unity 物体运动 之 物体按规定路线运动的使用

10、运行场景,即可看到物体按路线行进,具体如下图

Unity 物体运动 之 物体按规定路线运动的使用

11、到此,《Unity 物体运动 之 物体按规定路线运动的使用》讲解结束,谢谢

  • VisualStudio如何添加窗体控件#校园分享#
  • unity如何重新加载场景
  • Axure怎样组合图形?
  • U3D如何对物体进行多选操作
  • unity3d使用VS2010编写C#代码
  • 热门搜索
    建军节手抄报内容 以环保为主题的手抄报 a4手抄报版面设计图 开学手抄报简单又好画 饮食与健康手抄报 绿色校园手抄报内容 与法同行手抄报 美丽的家乡手抄报 关于宇宙的手抄报 改革开放四十周年手抄报