rotating an object back to the origin

hey, i’ pretty new to scripting and i have some basic problems.

actually i want to have a cylinder to be rotated in its center by the arrow keys (left and right). whenever no key is pushed it should be roated back to the origin, depending on which way is shorter, either left or right.

thus i made a script for the input of the keys and attached it to the object:

using UnityEngine;
using System.Collections;

public class rotate : MonoBehaviour {

void Update() {

if (Input.GetKey(“left”)) {
transform.Rotate(Vector3.left * Time.deltaTime * 400);
}

if (Input.GetKey(“right”)) {
transform.Rotate(Vector3.right * Time.deltaTime * 400);
}

}
}

this is how i imagined how it would work:

  1. save the origin (?)
  2. check if no keys are pushed
  3. check whether rotating back the left way to the origin or the right way is shorter.
  4. stop when the original position is reached.

would be nice if you could get me some hints how to deal with this :slight_smile:

Sure thing man. If you like the way your input works, and just want it to rotate back to some particular rotation when there is none, try this when there is no input:

transform.rotation = Quaternion.Lerp( transform.rotation, Quaternion.Identity, Time.deltaTime * 400 );

There are many common ways to manipulate the transforms of objects, and which method to use will always depend on how you want it to behave. This way seems like the quickest answer, but it’s not a very thorough one. There’s plenty of newbie-friendly info on such topics here at the forum and elsewhere - always make an effort to research!

Cheers,

Store the Quaternion value of the rotation at start.
Then in update, if no key pressed, use rotateTowards() that stored value.