Stop Gameobject reotationg constantly wne button is bressed?


I have a game object I would like too rotate to a specific rotation when the space bar is pressed or held down. I am currently using this code

GameObject.transform.Rotate (0, RotationAmmount, 0);

Currently, when I press space or hold the spacebar down the gameobject keeps rotating (adding the rotation amount every frame), how do I change the code so the gamobject stays at the rotation set in the RotationAmmount variable even if the spacebar is held down? It needs to be rotated on its local axis.


Transform.Rotate() rotates GameObject by a given Vector3, and you need to set rotation to a given Vector3, thus you can just use :

transform.rotation = new Vector3(0, RotationAmmount, 0);

If you need the action to be smooth, you can use Quaternion.Slerp().

It would be something like this (untested):

float t = 0f;
Quaternion desiredRotation = Quaternion.Euler(0, RotationAmmount, 0);

void Update()
            transform.rotation = Quaternion.Slerp(transform.rotation, desiredRotation, t);
            t += Time.deltaTime;

When local rotation is needed, then instead of transform.rotation, use transform.localRotation.
Also keep in mind, that Quaternion.Slerp() has to be called either from Update(), or from coroutine.