📜  头腰跟随鼠标相机脚本 (1)

📅  最后修改于: 2023-12-03 15:23:44.985000             🧑  作者: Mango

头腰跟随鼠标相机脚本

这个脚本可以让相机的头腰部位跟随鼠标的移动方向来改变相机的角度,从而实现更自然的相机跟随效果。

实现思路

该脚本使用了Unity引擎自带的Input系统来获取鼠标的移动方向,并通过代码来控制相机的旋转角度。具体实现步骤如下:

  1. 在制定游戏对象的相机上添加该脚本。
  2. 将游戏对象的相机的头腰部位和目标点绑定,通过改变相机与目标点之间的距离来控制相机的仰角。
  3. 使用Input系统获取鼠标的X轴和Y轴移动方向,然后通过旋转操作来改变相机与目标点的旋转角度。
代码片段

以下是该脚本的代码片段:

using UnityEngine;

public class FollowMouseCamera : MonoBehaviour
{
    public Transform target;
    public float distance = 5.0f;
    public float sensitivity = 3.0f;
    public float smoothing = 2.0f;

    private Vector2 _mouseLook;
    private Vector2 _smoothV;

    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
    }

    void Update()
    {
        var mouseDelta = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
        mouseDelta = Vector2.Scale(mouseDelta, new Vector2(sensitivity * smoothing, sensitivity * smoothing));
        _smoothV.x = Mathf.Lerp(_smoothV.x, mouseDelta.x, 1f / smoothing);
        _smoothV.y = Mathf.Lerp(_smoothV.y, mouseDelta.y, 1f / smoothing);
        _mouseLook += _smoothV;

        transform.localRotation = Quaternion.AngleAxis(-_mouseLook.y, Vector3.right);
        target.rotation = Quaternion.AngleAxis(_mouseLook.x, Vector3.up);
        transform.position = target.position - (target.rotation * Vector3.forward * distance);
    }
}

该脚本使用了 StartUpdate 两个方法来实现相机的跟随逻辑。其中,Start 方法用于锁定鼠标指针,而 Update 方法用于实时获取鼠标移动方向,并根据鼠标移动方向来控制相机的旋转和位置。具体实现步骤已在上面的实现思路中详细介绍。

以上是关于头腰跟随鼠标相机脚本的介绍和代码片段,希望对您有所帮助!