我一直在为3D FPS进行移动,除了相机移动外,一切运行良好。
我设置为根据光标在X轴上旋转刚体,并根据光标在Y轴上旋转相机。
问题在于Y轴没有限制,你可以在你身后看甚至做多次360转。我对Clamp没有经验。
我的两个脚本控制播放器。
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);*/
}
}
请建议。
答案 0 :(得分:1)
我假设你想限制最大值和最小值之间的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);