Unity 物体运动 之 物体按规定路线运动的使用。本节介绍,在Unity游戏开发中,如何使用物体按照指定路线运动的简单案例,具体如下
工具/原料
Unity
Transform.Translate
一、知识要点
1、Transform.Translate:1)功能简述public void哌囿亡噱Translate(Vector3translation,SpacerelativeTo= Sp锾攒揉敫ace.Self);Moves the transform in the direction and distance oftranslation.IfrelativeTois 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.) IfrelativeTois 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”具体人内容如下:usingUnityEngine;publicclassWayPoints:MonoBehaviour{publicstaticTransfor罪焐芡拂m[]wayPoints;voidAwake(){intcount=transform.childCount; wayPoints=newTransform[count];for(inti=0;i<count;i++){wayPoints[i]=transform.GetChild(i); }}}
7、在“Move”进行代码编辑,具体代码和代码说明如下图
8、“Move”具体人内容如下:usingUnityEngine;publicclassMove:MonoBehaviour{publicfloatspe髫潋啜缅ed=5;privateTransform[]ways; privateintindex;//Usethisforinitialization voidStart(){ways=WayPoints.wayPoints; index=0; } //Updateiscalledonceperframe voidUpdate(){MoveTo(); }voidMoveTo(){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 物体运动 之 物体按规定路线运动的使用》讲解结束,谢谢