I have a camera and player movement system in 2 scripts that are linked. I want to restrict the camera movement, so I tried the use a clamp. For the most part, it worked, but when I rotated my camera up to 0 on the x-axis, it violently was rotated downwards again. I don’t know what’s wrong.
[RequireComponent(typeof(Rigidbody))]
public class PlayerMotor : MonoBehaviour
{
[SerializeField] private Camera cam;
private Vector3 velocity = Vector3.zero;
private Vector3 rotation = Vector3.zero;
private Vector3 camRotation = Vector3.zero;
[SerializeField] Animator animator;
private Rigidbody rb;
private void Start()
{
rb = GetComponent<Rigidbody>();
cam = GetComponentInChildren<Camera>();
animator = transform.Find("PlayerModel").GetComponent<Animator>();
}
//Gets a movement vector
public void Move(Vector3 Velo)
{
velocity = Velo;
}
//Gets rotational vector
public void Rotate(Vector3 rota)
{
rotation = rota;
}
public void RotateCamera(Vector3 camRota)
{
camRotation = camRota;
}
//run every physics iteration
void FixedUpdate()
{
PerformMovement();
PerformRotation();
}
//Perform movement based on velocity
void PerformMovement()
{
if (velocity != Vector3.zero)
{
rb.MovePosition(transform.position + velocity * Time.fixedDeltaTime);
animator.SetFloat("Speed", 1);
}
else
{
animator.SetFloat("Speed", 0);
}
}
//Quaternion.Euler TAKES ONLY XYZ AXES
void PerformRotation()
{
Vector3 camAngles = cam.transform.localEulerAngles;
rb.MoveRotation(transform.rotation * Quaternion.Euler(rotation));
if (cam != null)
{
Transform camTrans = cam.transform;
cam.transform.Rotate(camRotation);
camTrans.localEulerAngles = new Vector3(Mathf.Clamp(camTrans.localEulerAngles.x, -90, 50), 0, 0);
}
}
}
PlayerController
[RequireComponent(typeof(PlayerMotor))]
public class PlayerController : MonoBehaviour {
[SerializeField] private float speed = 12;
[SerializeField] private float sensitivity = 3;
[SerializeField] private PlayerMotor motor;
[SerializeField] private Rigidbody rb;
[SerializeField] private Camera cam;
void Start()
{
motor = GetComponent<PlayerMotor>();
cam = transform.Find("MainCamera").GetComponent<Camera>();
rb = GetComponent<Rigidbody>();
}
private void Update()
{
//Calculate movement velocity as vector3
float xMov = Input.GetAxisRaw("Horizontal");
float zMov = Input.GetAxisRaw("Vertical");
Vector3 movHorizontal = transform.right * xMov;
Vector3 movVertical = transform.forward * zMov;
//final movement vector
Vector3 velocity = (movHorizontal + movVertical).normalized * speed;
//apply movement
motor.Move(velocity);
//calculate rotation as vector3 (turning)
float yRot = Input.GetAxisRaw("Mouse X");
Vector3 rotation = new Vector3(0, yRot, 0) * sensitivity;
//Apply player rotation
motor.Rotate(rotation);
//calculate camera rotation as vector3
float xRot = Input.GetAxisRaw("Mouse Y");
Vector3 camRotation = new Vector3(-xRot,0,0) * sensitivity;
//Apply camera rotation
motor.RotateCamera(camRotation);
if (Input.GetKey(KeyCode.LeftShift))
{
speed = 20;
}
else
{
speed = 12;
}
}
}