Rotate on keyDown, and rotate back to place...

Hey guys,

Trying to do something simple but I'm stuck. I have a 2D airplane that I want to rotate when holding down the UP or DOWN keyarrows, and I want it to rotate back to 0 when you release the key. I'm almost there... but rotating back to 0 is the problem, because it never reaches 0. This is the code:

    float smooth = 5f;
    float tiltAroundZ;
    Quaternion target;

    if (Input.GetKey(KeyCode.UpArrow))
    {
        tiltAroundZ = Input.GetAxis("Vertical") * maxUpRotation;
        target = Quaternion.Euler(transform.rotation.x, this.transform.rotation.y, tiltAroundZ);
        GoUp();

    }
    else if (Input.GetKey(KeyCode.DownArrow))
    {
        tiltAroundZ = Input.GetAxis("Vertical") * maxDownRotation;
        target = Quaternion.Euler(transform.rotation.x, this.transform.rotation.y, -tiltAroundZ);
        GoDown();
    }
    else
    {
        target = Quaternion.Euler(transform.rotation.x, this.transform.rotation.y, 0);
        this.transform.rotation = Quaternion.Slerp(transform.rotation, target, Time.deltaTime * smooth);

    }

1 Answer

1

A couple of things. You don't really need

 if (Input.GetKey(KeyCode.UpArrow))

Input.GetAxis is already mapped to the arrow keys. Also, have you tried eliminating the Slerp function altogether? Input.GetAxis outputs a value between -1 and 1 and you can just multiply the value by Time.deltaTime. There's a simple example in the scripting reference here:

http://unity3d.com/support/documentation/ScriptReference/Input.GetAxis.html

edit: by the way, the problem you're having may in part be due to the fact that your rotation is constantly changing. Slerp is interpolating between the current rotation and the target so you never quite get there. This problem comes up a lot in the forums.

Hi, thanks for your answer. Yes... I think that is the problem, it is never reaching the target... which is Zero. I'm not quite sure how to fix that though...