unity相机跟随代码

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; // 更新相机位置
    }
}

        在上述代码中,我们定义了一个 target 变量来指定需要跟随的物体。offset 变量用来指定相机和物体之间的距离。smoothSpeed 变量用来指定相机的跟随速度。在 LateUpdate() 函数中,我们首先计算出相机应该在的位置 desiredPosition。然后使用 Lerp() 函数将相机缓慢移动到目标位置,并使用 transform.position 更新相机位置。

你可以将该脚本挂载在相机上,然后将需要跟随的物体赋值给 target 变量,即可实现相机跟随。

猜你喜欢

转载自blog.csdn.net/Steel_nails/article/details/133897822