Evangelion88
Evangelion88

Reputation: 1

How to restrict the rotation of an object when using transform.Rotate()?

I'm trying to limit the rotation of an object on the x-axis. The rotation is performed as follows:

float moveVertical = Input.GetAxis("Vertical");
transform.Rotate(moveVertical * rotationRate * Time.deltaTime, 0, 0);

I tried to do it like this:

   if( transform.rotation.x > -89f && tranform.rotation.x < 89f) 
{
   transform.Rotate(moveVertical * rotationRate * Time.deltaTime, 0, 0); 
}

But then Unity breaks, and PlayMode doesn't turn on at all... I have to restart the program through the task Manager.

Upvotes: 0

Views: 151

Answers (1)

JLum
JLum

Reputation: 118

It appears the reason your Unity doesn't play is because you have a mistake in your code and "transform" is spelled wrong in your if statement, so this should fix that:

if(transform.rotation.x > -89f && transform.rotation.x < 89f) 
{
   transform.Rotate(moveVertical * rotationRate * Time.deltaTime, 0, 0); 
}

If that isn't the case please let us know what error you are getting when trying to run Unity.

Also with your code you aren't limiting the rotation about the x-axis between -89 and 89 as you are checking the wrong variable. rotation.x refers to the x value of the quaternion which is likely not what you are looking for. To check the amount that an objected is rotate by you should instead use:

if(transform.eulerAngles.x > -89f && transform.eulerAngles.x < 89f) 
{
   transform.Rotate(moveVertical * rotationRate * Time.deltaTime, 0, 0); 
}

Upvotes: 1

Related Questions