Search Unity

Limit y rotation

Discussion in 'General Discussion' started by marcosis, Mar 30, 2021.

  1. marcosis

    marcosis

    Joined:
    Nov 5, 2018
    Posts:
    22
    Hey,

    I have the below script which works really well for looking around my scene. I was wondering if someone could help me limit the maximum rotation for the y axis.

    Currently, when you hold the mouse button down you can move your mouse forward to look down and go as far as all the way through the floor!

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class NewBehaviourScript : MonoBehaviour
    6. {
    7.    
    8.         Vector2 rotation = new Vector2(0, 0);
    9.         public float speed = 3;
    10.  
    11.         void Update()
    12.         {
    13.         if (Input.GetMouseButton(0)) {
    14.             rotation.y += Input.GetAxis("Mouse X");
    15.             rotation.x += -Input.GetAxis("Mouse Y");
    16.             transform.eulerAngles = (Vector2)rotation * speed;
    17.         }
    18.     }
    19.     }
    Any help would be much appreciated!

    Cheers
     
  2. sxa

    sxa

    Joined:
    Aug 8, 2014
    Posts:
    741
    well, what about not doing the addition to rotation.y without any check or limit on the resulting value?

    A few thousand clues might be found by googling 'unity restrict rotation'
     
  3. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    13,569
    Mathf.Clamp
     
  4. marcosis

    marcosis

    Joined:
    Nov 5, 2018
    Posts:
    22
    Congrats on the sarcasm. I'm currently in the process of learning how to read script, so when im looking around online, as the answers i found didn't match the part that i had that was working, i didnt know how to merge the 2.

    Its fine now @neginfinity pointed me in the right direction and now the issue is resolved.

    Cheers