简单的Unity3D摄像机跟随主角的代码:

在Unity3D软件创建 脚本文件CameraFollow,并打开脚本文件,使用下面的代码:

using UnityEngine;

public class CameraFollow : MonoBehaviour
{
    public Transform target; // 跟随的目标,即主角
    public float smoothSpeed = 0.125f; // 摄像机跟随的速度
    public Vector3 offset; // 摄像机与主角之间的距离

    void LateUpdate()
    {
        Vector3 desiredPosition = target.position + offset; // 计算摄像机应该移动到的位置
        Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed); // 平滑移动摄像机
        transform.position = smoothedPosition; // 更新摄像机的位置
    }
}

该脚本中有三个公共变量:

  1. target:跟随的目标,即主角,需要在Inspector面板中手动设置。
  2. smoothSpeed:摄像机跟随的速度,用于控制摄像机移动的平滑程度。
  3. offset:摄像机与主角之间的距离,也需要手动设置。

在LateUpdate()函数中,首先计算出摄像机应该移动到的位置,然后使用Lerp函数平滑移动摄像机,并更新摄像机的位置。由于LateUpdate()函数在Update()函数之后执行,因此可以确保摄像机在主角移动后才进行移动,避免出现卡顿的情况。

将这段代码挂载到摄像机上,然后将主角的Transform组件赋值给target变量即可。如果需要调整摄像机与主角之间的距离,可以修改offset变量的值。

猜你喜欢

转载自blog.csdn.net/WMcsdn11124/article/details/130306673