Unity 实用技巧 之 物体始终朝向目标物体的实现
1、Transform.LookAt:
1)函数形式
(1)public void LookAt(Transform target, Vector3 worldUp = Vector3.up);
(2)public void LookAt(Vector3 worldPosition, Vector3 worldUp = 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 the worldUp vector. If you leave out the worldUp parameter, the function will use the world y axis. worldUp is only a hint vector. The up vector of the rotation will only match the worldUp vector if the forward direction is perpendicular to worldUp.
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 实用技巧 之 物体始终朝向目标物体的实现》讲解结束,谢谢