前言
- 随便写了个demo,记录一下思路,忘记的时候好温顾
- 没有教学的价值,可以参考一下
step1:获取鼠标的横纵坐标
var horizontalAxis = Input.GetAxis("Mouse X");
var verticalAxis = Input.GetAxis("Mouse Y");
- 注意一件事就是鼠标不动的时候,即使之前怎么移动都会回到(0,0)
- 这个输入只是记录的是瞬时的坐标
- 如果希望镜头保持的话,需要将上一时刻的旋转角获取并与这一时刻的输入进行相加
tmpHorizontalAxis += horizontalAxis;
tmpVerticalAxis += verticalAxis;
Step2:限制视角上下的旋转角度
rotationVector3.x = Mathf.Clamp(-tmpVerticalAxis * mouseSensitive, -65f, 65f);
Step3:通过旋转相机角度来控制游戏物体的旋转
- 将脚本赋给相机,并将外部需要控制旋转的游戏对象赋给脚本中的transform就可以了
- 需要注意的是,如果一个人物在平面上,只用同步相机绕y轴旋转的角度进行左右旋转就可以了
transform.rotation = Quaternion.Euler(rotationVector3.x, rotationVector3.y, 0);
bodyTransform.rotation = Quaternion.Euler(0, rotationVector3.y, 0);
Step4:鼠标居中
[DllImport("user32.dll")]
public static extern int SetCursorPos(int x, int y);
- 然后再update或者fixedUpdate中调用方法即可
SetCursorPos((int) Screen.width / 2, (int) Screen.height / 2);
完整脚本如下:
using System.Runtime.InteropServices;
using UnityEngine;
public class FPInputControlScript : MonoBehaviour
{
[SerializeField] private Transform bodyTransform;
private Transform cameraTransform;
private Vector3 rotationVector3;
public float mouseSensitive;
private float tmpHorizontalAxis;
private float tmpVerticalAxis;
[DllImport("user32.dll")]
public static extern int SetCursorPos(int x, int y);
private void Start()
{
cameraTransform = transform;
}
private void Update()
{
var horizontalAxis = Input.GetAxis("Mouse X");
var verticalAxis = Input.GetAxis("Mouse Y");
tmpHorizontalAxis += horizontalAxis;
tmpVerticalAxis += verticalAxis;
rotationVector3.x = Mathf.Clamp(-tmpVerticalAxis * mouseSensitive, -65f, 65f);
rotationVector3.y = tmpHorizontalAxis * mouseSensitive;
transform.rotation = Quaternion.Euler(rotationVector3.x, rotationVector3.y, 0);
bodyTransform.rotation = Quaternion.Euler(0, rotationVector3.y, 0);
SetCursorPos((int) Screen.width / 2, (int) Screen.height / 2 + 100);
}
}
|