# How to rotate a gameobject to the specific angle

I have tree model that is being rotating .After certain angle it should stop rotating.I have done a sample code.But the tree is not stopping.

void Update () {

//transform.Rotate (0f,0,0.5f*Time.deltaTime);
//transform.Rotate (Vector3.forward,Time.deltaTime*5);
transform.Rotate (0f,0f,time);
Debug.Log(time);
time+=0.5f;
if(time==5.5f)
{
transform.eulerAngles=Vector3.zero;
}


}

From the above code I need to stop the rotation when the z axis value is 5.5f.How can I do this . Please help me.

Instead of doing: if (time == 5.5f), you need to do: if (time >= 5.5f).

The rotation is stopping for a short amount of time (One update), but then the time variable is increased the next update. Its not equal to 5.5 anymore, so the rotation continues.

• Also, you should avoid using == with floats as sometimes can be problem if the number cannot be represent exactly. – T. Kiley Jun 8 '15 at 12:49

It's pretty easy, once it reaches 5.5f indeed the rotation vector should be zero, but this is Update() we're talking about. If we take what you have written outside of the if statement :

transform.Rotate (0f,0f,time);
Debug.Log(time);
time+=0.5f;


On every frame, your object will rotate by 0.5 eulerAngle, then 1, then 1.5, infinitely. To fix this you can just make a bigger if statement like this :

time+=0.5f;
if(time!=5.5f) {
transform.Rotate (0f,0f,time);
}
else
{
transform.eulerAngles=Vector3.zero;
}


This should logically work.

void Update () {
//if you are past the amount of degrees, then you don't need to rotate more.
if (this.transform.rotation.eulerAngles.z > /*amount of degrees*/ 5.5f) return;

//rotate more
this.transform.Rotate (0, 0, 0.1f);
}


Or better, I would make a quaternion of the starting angle and the end angle ( using: http://docs.unity3d.com/ScriptReference/Quaternion.Euler.html ), then I would lerp ( using: http://docs.unity3d.com/ScriptReference/Quaternion.Lerp.html ) between the two values.

Hope that helps!