Limit local Rotations on one axis


i got problems with limiting rotation of cylinder on one axis. I tried almost everything from eulers to quaternions, but i am sure it is only my lack of experience why i am not able to pull this out.

I managed to limit its rotations on X axis, but strangely same code doesnt work for Z axis. Here is the code i got for limiting the X axis.

I know eulerAngles shouldnt be used for setting values separately, but this is only solution that worked for me on X axis.

// Limit rotations

    if(transform.rotation.eulerAngles.x > 89)
        transform.rotation.eulerAngles.x = 89;

else if(Input.GetButton("up"))
    if(transform.rotation.eulerAngles.x < 50)
        transform.rotation.eulerAngles.x = 50;



Thanks in advance.


It's perfectly fine to set rotation using the classic three X/Y/Z rotations (the ones you see in the Editor for rotation, now called Euler angles.) The rule is you have to set them all at once, or else funny things can happen.

To do this, best to have separate vars for the rotations. After you set the euler angles, Unity may convert -10 to 350, or other odd things. If you treat your locals as the "Master copy", it won't matter.

float facing=0, spin=0; // spin is local zRotation, like on a bullet

// somewhere in Update, or FixedUpdaye:

// many ways to set facing and spin. Using arrow keys for a quick test:
facing += Input.GetAxis("Horizontal")*120*Time.deltaTime;
//            standard way to spin at 30 degrees/second:
spin += Input.GetAxis("Vertical")*30*Time.deltaTime;

// limit some number:
spin = Mathf.Clamp(spin, -30, 30);  // the cool kids' way
if(spin>30) spin =30;    // normal persons' way
if(spin<-30) spin =-30;

// this is how the Unity docs say to safely set euler rotations:
transform.rotation = Quaternion.Euler(0,facing,spin);

I fix your script for rotate limiting, but you can´t add numbers lower than 1 and higher than 359 because it is in degrees.

private var firsEnd = false;
private var secondEnd = false;

function OnGUI(){
firsEnd = transform.rotation.eulerAngles.y > 359;
secondEnd = transform.rotation.eulerAngles.y < 1;

function Update(){    

if (firsEnd) transform.rotation.eulerAngles.y = 359;
if (secondEnd) transform.rotation.eulerAngles.y = 1;

Sorry for my bad englis. I´m from Czech

for anyone else trying to do this - the easiest way is to use the Unity Rotation Constraint script - Add Component>Script>Rotation Constraint