📅  最后修改于: 2023-12-03 15:23:44.985000             🧑  作者: Mango
这个脚本可以让相机的头腰部位跟随鼠标的移动方向来改变相机的角度,从而实现更自然的相机跟随效果。
该脚本使用了Unity引擎自带的Input系统来获取鼠标的移动方向,并通过代码来控制相机的旋转角度。具体实现步骤如下:
以下是该脚本的代码片段:
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);
}
}
该脚本使用了 Start
和 Update
两个方法来实现相机的跟随逻辑。其中,Start
方法用于锁定鼠标指针,而 Update
方法用于实时获取鼠标移动方向,并根据鼠标移动方向来控制相机的旋转和位置。具体实现步骤已在上面的实现思路中详细介绍。
以上是关于头腰跟随鼠标相机脚本的介绍和代码片段,希望对您有所帮助!