Lock the y axis (on an object that's not a rigid body) c#

Hi everybody,

So i’m making a game in which you control a plane (a flat square, not a flying plane haha) to make the objects on it move according to the rotation.

You control the x axis with the Up and Down arrows and the z axis with the Left and Right arrows.

Everything works just fine but I noticed that my plane, somehow, moves as well on the y axis the more you make the plane rotate. I really don’t know why. I tried to force the y axis to be locked on 0 but it makes the whole plan (every axis) locked on 0.

Here’s my code (the part where I lock the y axis is in the end):

		Vector3 tmp;
		
		tmp = transform.eulerAngles;
		tmp.y = 0;
		
		if(Input.GetKey (KeyCode.UpArrow)){ 
				if (plan.transform.eulerAngles.x<angleMax || plan.transform.eulerAngles.x>180+angleMax){
					plan.transform.Rotate(rotation_x);
				}
		}
		if(Input.GetKey (KeyCode.DownArrow)){
				if (plan.transform.eulerAngles.x>360-angleMax || plan.transform.eulerAngles.x<180-angleMax){
					plan.transform.Rotate(-rotation_x);
				}
		}


		if(Input.GetKey (KeyCode.LeftArrow)){
				if (plan.transform.eulerAngles.z<angleMax || plan.transform.eulerAngles.z>180+angleMax){
					plan.transform.Rotate(rotation_z);
				}
		}
		if(Input.GetKey (KeyCode.RightArrow)){
				if (plan.transform.eulerAngles.z>360-angleMax || plan.transform.eulerAngles.z<180-angleMax){
					plan.transform.Rotate(-rotation_z);
				}
		}
		if(plan.transform.eulerAngles.y != 0){  //this is where I try to lock it
                plan.transform.eulerAngles = tmp;  
        }  

Thanks ! :slight_smile:

Unity uses Quaternions internally to represent rotations and there are more than one set of EulerAngles that can represents the same Quaternion, so you don’t always get the EulerAngles back that you put in.

if you just want to rotate around x and z, keep the current rotation in float variables rotX, rotZ, let your input code only manipulate those variables and at the end of set the Rotation to new EulerAngles.

So you only write EulerAngles and never read from them.

This should fix your problems.