Unity 实用技巧 之 物体始终朝向目标物体的实现

 时间:2026-02-13 09:37:56

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,新建一个空工程,具体如下图

Unity 实用技巧 之 物体始终朝向目标物体的实现

2、在工程中新建一个脚本,脚本可以命名为“LookAtTarget”,然后双击脚本或者右键“Open C# Project”打开脚本,具体如下图

Unity 实用技巧 之 物体始终朝向目标物体的实现

Unity 实用技巧 之 物体始终朝向目标物体的实现

3、在打开的“LookAtTarget”脚本上编写代码,首先设置一个朝向目标对象变量,然后在Update函数中,实现母体朝向,一种方式是全身朝向,物体会倾斜,一种转向物体,而不会倾斜,两种方法,具体使用选用一种方法即可,具体代码和代码说明如下图

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

Unity 实用技巧 之 物体始终朝向目标物体的实现

6、运行场景,在“Scene”视图里面拖到“Camera”,即会看到“Cube”转动始终朝向摄像机,具体如下图

Unity 实用技巧 之 物体始终朝向目标物体的实现

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

  • teamviewer远程电脑桌面没有背景图?
  • AxureRP添加线性渐变教程
  • MD9.0点击鼠标右键不出菜单
  • LOD生成器的基本用法
  • VEGAS 10.0崩溃后项目补救
  • 热门搜索
    英联邦运动会 消防安全知识黑板报 安全帽的作用 做作什么意思 冬季传染病预防知识 胖大海的功效与作用 做寿司用什么米 什么是化学键 梦幻西游仙玉有什么用 运动会作文500字