在Unity中,可以使用以下代码实现相机跟随物体的功能:

using UnityEngine;

public class CameraFollow : MonoBehaviour
{
    public Transform target; // 要跟随的物体
    public Vector3 offset; // 相机与物体的偏移量

    private void LateUpdate()
    {
        // 计算相机的目标位置
        Vector3 targetPosition = target.position + offset;

        // 使用平滑的移动方式将相机移动到目标位置
        transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime * 5f);
    }
}

将上述代码添加到一个空物体上,并将要跟随的物体赋值给target变量。可以通过调整offset变量来控制相机与物体之间的偏移量。在每一帧的LateUpdate方法中,计算出相机的目标位置,并使用Lerp方法平滑地将相机移动到目标位置

Unity跟随物体的代码

原文地址: http://www.cveoy.top/t/topic/hAdA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录