Search code examples
androidunity-game-enginerotationunityscriptunity3d-2dtools

Unity2D - How to rotate a 2D object on touch/click/press


First of all, I'll let you know that I'm new to Unity and to coding overall (I do know some very basic javascript coding). My question: How can I rotate a 2D object (prefab) 120 degrees on a certain axis (in my case the z-axis, so it rotates like you're looking at a steering wheel) every time I touch on the screen. Right now I have it like this:

function TouchOnScreen ()
{
    if (Input.touchCount > 0)
    {
        var touch = Input.touches[0];
        if (touch.position.x < Screen.width/2)
        {
            transform.rotation = Quaternion.Euler(0,0,120);
            Debug.Log("RotateRight");
        }
        else if (touch.position.x > Screen.width/2)
        {
            transform.rotation = Quaternion.Euler(0,0,-120);
            Debug.Log("RotateLeft");
        }
    }
}

This code rotates the object whenever I press on a certain side of the screen, but not how I want it to. I want it to rotate so you see the object rotating from A to B, but not (like it is now) in one frame from A to B. Also, this code lets me only rotate one time to each direction.

How can I make it that whenever I press on a certain side of the screen, that it adds or subtracts to/from the previous rotated angle, so I can keep on rotating.

NOTE: Please use javascript, and if you know a simpler code, let me know!

Help is highly appreciated, thanks in advance!


Solution

  • Instead of

            transform.rotation = Quaternion.Euler(0,0,-120);
    

    You use:

            var lSpeed = 10.0f; // Set this to a value you like
            transform.rotation = Quaterion.Lerp ( transform.rotation, Quaternion.Euler(0,0,-120), Time.deltaTime*lSpeed);