Y 轴摄像机移动



我一直在为 3D FPS 制作运动,除了相机运动之外,一切都运行良好。

我将其设置为基于光标在 X 轴上旋转刚体,并根据光标在 Y 轴上旋转相机。

问题是Y轴没有限制,你可以看你的身后,甚至可以做多个360转。我没有使用夹子的经验。

我的两个脚本控制播放器。

using UnityEngine;
[RequireComponent(typeof(PlayerMotor))]
public class PlayerControler : MonoBehaviour {
private float speed = 5f;
float lookSensitivity = 70f;
private PlayerMotor motor;
void Start ()
{
motor = GetComponent<PlayerMotor>();
}
void Update ()
{
float _xMov = Input.GetAxis("Horizontal");
float _zMov = Input.GetAxis("Vertical");
Vector3 _movHorizontal = transform.right * _xMov;
Vector3 _movVertical = transform.forward * _zMov;
Vector3 _velocity = (_movHorizontal + _movVertical).normalized * speed;
motor.Move(_velocity);
//Turning
float _yRot = Input.GetAxis("Mouse X");
Vector3 _rotation = new Vector3 (0f, _yRot, 0f) * lookSensitivity;
motor.Rotate(_rotation);
//Camera Rotation
float _xRot = Input.GetAxis("Mouse Y");
Vector3 _cameraRotation = new Vector3 (_xRot, 0f, 0f) * lookSensitivity;
motor.RotateCamera(-_cameraRotation);
}
}

using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class PlayerMotor : MonoBehaviour {
[SerializeField]
private Camera cam;
private Vector3 velocity = Vector3.zero;
private Vector3 rotation = Vector3.zero;
private Vector3 cameraRotation = Vector3.zero;
private Rigidbody rb;
void Start ()
{
rb = GetComponent<Rigidbody>();
}
public void Move (Vector3 _velocity)
{
velocity = _velocity;
}
public void Rotate (Vector3 _rotation)
{
rotation = _rotation;
}
public void RotateCamera (Vector3 _cameraRotation)
{
cameraRotation = _cameraRotation;
}
void FixedUpdate ()
{
PerformMovement();
PreformRotation();
}
void PerformMovement ()
{
if (velocity != Vector3.zero)
{
rb.MovePosition(rb.position + velocity * Time.fixedDeltaTime);
}
}
void PreformRotation ()
{
rb.MoveRotation(rb.rotation * Quaternion.Euler (rotation));
if (cam != null)
{ 
cam.transform.Rotate(cameraRotation);
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
/*cameraRotation = Mathf.Clamp(cameraRotation.x, -89f, 89f);
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
localRotation = Quaternion.Euler(cameraRotation, rotation, 0);*/
}
}

请指教。

我假设您想限制最大值和最小值之间的 x 旋转,这就是夹紧的意思。

在此行之后

float _xRot = Input.GetAxis("Mouse Y");

首先,请确保角度介于 0 和 360 之间:

if (_xRot < -360F) _xRot += 360F;
if (_xRot > 360F) _xRot -= 360F;

然后将其限制在最大值和最小值之间:

float min = -70f;
float max = 70f;
_xRot = Mathf.Clamp(_xRot, min, max);

最新更新