Temporary Rotation

Hi, guys! I have a very short question. I would like to have an object rotate upwards, downwards, left, and right when I press the respective keys.

2 issues with this though:

  1. I’d like to set boundaries for how far it can rotate
  2. I’d like to make it go back to it’s original rotation after I let go of a key. But not suddenly. As in I’d like it to fade back. I think that’s done with Lerps or something.

Please help! I am utterly confused when it comes to the world of rotations. :slight_smile:

Thanks!- YA

Within a Script, a function called Update() is called every frame. Within this Update function, one can code a call to Input.GetKey(). This will return true if a specific key is pressed. Based on this, you now have knowledge that a key has been pressed. Now let us talk about rotation. The rotation of a Game Object can be determined from its Transform component. This is stored in the transform.rotation property. One should save the start value of this property when NO keys are pressed. When a key is pressed, one can then start changing the value of this property based on the key … for example, the up arrow rotates around the X axis.

You want to consider the concept of the rate of rotation. Think of this as a value measured in degrees per second. For example, if you want to rotate at 10 degrees per second, you would rotate by 10*Time.deltaTime within the Update function. The Time.deltaTime is the number of seconds since the last time Update was called.

When no keys are pressed, you want to return to your original rotation over a period of time. You can do this using the Vector3 Lerp function again using Time.deltaTime as a rate.

Nevermind I figured it out. Here is the script:

    // Smoothly tilts a transform towards a target rotation.
var tiltAngle = 30.0;
var MoveTiltspeed = 5.0;
function Update () {
    var tiltAroundZ = Input.GetAxis("Horizontal") * tiltAngle;
    var tiltAroundX = Input.GetAxis("Vertical") * tiltAngle;
    var target = Quaternion.Euler (-tiltAroundX, 0, -tiltAroundZ);
    // Dampen towards the target rotation
    // Dampen speed is movement speed * 1.2 so that they stay in proportion realistically
    transform.rotation = Quaternion.Slerp(transform.rotation, target, Time.deltaTime * MoveTiltspeed*1.2);;
    var x = Input.GetAxis("Horizontal") * Time.deltaTime * MoveTiltspeed;
    var y = Input.GetAxis("Vertical") * Time.deltaTime * MoveTiltspeed;
    transform.Translate(x, y, 0, Space.World);
}