Unity 物体运动 之 物体按规定路线运动的使用
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,新建一个工程,具体如下图

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

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


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

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

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”进行代码编辑,具体代码和代码说明如下图

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”,具体如下图


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

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