Unity中一个可以实现第一人称射击类游戏的摄像机控制方法,在此做一个纪录。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/**
* 在Player对象上创建一个Camera
* 将该脚本放到Camera上即可
*/
[RequireComponent(typeof(Camera))]
public class ShootCamera : MonoBehaviour
{
public GameObject player;
public Vector2 mouseLookSensitivity = new Vector2(5, 5);
//垂直方向上可旋转的最大角度
public Vector2 rotationXLimit = new Vector2(-87, 87);
//水平方向上可旋转的最大角度
public Vector2 rotationYLimit = new Vector2(-360, 360);
private float x_Angle = 0;
private float y_Angle = 0;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float x = Input.GetAxis("Mouse X");
float y = Input.GetAxis("Mouse Y");
x_Angle += (y * mouseLookSensitivity.y);
y_Angle += (x * mouseLookSensitivity.x);
x_Angle = ClampDegree(x_Angle, rotationXLimit.x, rotationXLimit.y);
y_Angle = ClampDegree(y_Angle, rotationYLimit.x, rotationYLimit.y);
//水平方向上基于Player对象的Y轴旋转
Quaternion playerQuaternion = Quaternion.AngleAxis(y_Angle, Vector3.up);
player.transform.rotation = playerQuaternion;
//垂直方向上基于Camera对象的X轴旋转
Quaternion cameraQuaternion = Quaternion.AngleAxis(x_Angle, Vector3.left);
this.transform.rotation = playerQuaternion * cameraQuaternion;
}
private float ClampDegree(float angle, float min, float max)
{
if (angle < -360)
{
angle += 360;
}
else if (angle > 360)
{
angle -= 360;
}
angle = Mathf.Clamp(angle, min, max);
return angle;
}
}