Unity 实用技巧 之 物体始终朝向目标物体的实现
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,新建一个空工程,具体如下图


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”为目标观察对象,具体如下图

7、到此,《Unity 实用技巧 之 物体始终朝向目标物体的实现》讲解结束,谢谢