Search Unity

Question How can i clamp the rotation

Discussion in 'Getting Started' started by OUTHMANEGA, Feb 12, 2022.

  1. OUTHMANEGA

    OUTHMANEGA

    Joined:
    May 9, 2020
    Posts:
    2
    hey guys, I was trying to clamp the rotation of the x-axis but for some reason, the z-axis kept changing from 180 to -180 degrees which messed up the clamping



    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Came: MonoBehaviour
    6. {
    7.     public float MouseSens;
    8.     float y;
    9.     float x;
    10.     // Start is called before the first frame update
    11.     void Start()
    12.     {
    13.         Cursor.lockState = CursorLockMode.Locked;
    14.     }
    15.  
    16.     // Update is called once per frame
    17.     void Update()
    18.     {
    19.         x -= Input.GetAxis("Mouse Y");
    20.         x = Mathf.Clamp(x, -90, 90);
    21.         y += Input.GetAxis("Mouse X");
    22.         transform.eulerAngles =  new Vector3(x, y, 0) * MouseSens;
    23.     }
    24. }

    I'm new to unity so if someone could help me it would be much appreciated, ty!!
     
  2. Gabrielmarket

    Gabrielmarket

    Joined:
    Feb 13, 2022
    Posts:
    1
    J'ai aussi le même problème :(
     

    Attached Files:

  3. OUTHMANEGA

    OUTHMANEGA

    Joined:
    May 9, 2020
    Posts:
    2
    Ay!! I'm back again, for some reason when I multiplied each variable separately it worked anyways for anyone who has the same problem here's how to fix it :
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Came : MonoBehaviour
    6. {
    7.     public float MouseSens;
    8.     float y;
    9.     float x;
    10.     void Start()
    11.     {
    12.         Cursor.lockState = CursorLockMode.Locked;
    13.     }
    14.     void Update()
    15.     {
    16.         x -= Input.GetAxis("Mouse Y") * MouseSens;
    17.         x = Mathf.Clamp(x, -90, 90);
    18.         y += Input.GetAxis("Mouse X") * MouseSens;
    19.         transform.eulerAngles =  new Vector3(x , y, 0);
    20.     }
    21. }