Unity 实用技巧 之 物体始终朝向目标物体的实现。物体随着目标物体而转动,使自己始终朝向目标物体。一种是物体全身动来十中面向目标物体;一种是不会上下动转向物体这样不会造成物体倾斜;本节介绍这两个方法的使用的简单案例,具体如下
工具/原料
Unity
LookAt
一、案例要点
1、Transform.LookAt:1)函数形式(1)public void雉搽妤粲LookAt(Transformtarget,Vector3worldUp= V髫潋啜缅ector3.up);(2)public voidLookAt(Vector3worldPosition,Vector3worldUp= Vector3.up);2)参数解释target:Object to point towards.worldUp:Vector specifying the upward direction.worldPosition:Point to look at.3)功能描述Rotates the transform so the forward vector points at /target/'s current position.Then it rotates the transform to point its up direction vector in the direction hinted at by theworldUpvector. If you leave out theworldUpparameter, the function will use the world y axis.worldUpis only a hint vector. The up vector of the rotation will only match theworldUpvector if the forward direction is perpendicular toworldUp.
二、Unity 实用技巧 之 物体始终朝向目标物体的实现
1、打开Unity,新建一个空工程,具体如下图
2、在工程中新建一个脚本,脚本可以命名为“LookAtTarget”,然后双击脚本或者右键“Open C# Project”打开脚本,具体如下图
3、在打开的“LookAtTarget”脚本上编写代码,首先设置一个朝向目标对象变量,然后在Update函数中,实现母体朝向,一种方式是全身朝向,物体会倾斜,一种转向物体,而不会捋捷巳猓倾斜,两种方法,具体使用选用一种方法即可,具体代码和代码说明如下图
4、“LookAtTarget”脚本具体内容如下:using UnityEngine;public class LookAtTarget : MonoBehaviour { public Transform target; // Use this for initialization void Start () { } // Update is called once per frame void Update () { //当目标对象运动时,始终面向物体 //transform.LookAt(target); //当目标对象运动时,始终转向物体 //但是尽在Y轴上旋转,而不会上下旋转 //不造成物体倾斜 transform.LookAt(new Vector3(target.position.x, transform.position.y, target.position.z)); }}
5、脚本编译正确后,不到Unity界面,在场景中新建一个“Cube”,然后把脚本“LookAtTarget”挂上去,选中主摄像机“Camera”为目标观察对象,具体如下图
6、运行场景,在“Scene”视图里面拖到“Camera”,即会看到“Cube”转动始终朝向摄像机,具体如下图
7、到此,《Unity 实用技巧 之 物体始终朝向目标物体的实现》讲解结束,谢谢