Home > Net >  How to rotate a 2D object by 90 degrees in unity
How to rotate a 2D object by 90 degrees in unity

Time:03-25

I need to rotate 2D GameObject by 90 degrees by z axis. So I already tried transform.RotateAround but still rotates in a complete circle:

transform.RotateAround(target.transform.position, new Vector3 (0, 0, -90),
        50f * Time.deltaTime)

I need to stop it by 90. How can I do it?

enter image description here

CodePudding user response:

Create a coroutine that rotates based on deltaTime and keeps track of how far it has rotated, stopping once it hits 90. Use Mathf.Min to be sure not to rotate past 90.

private isRotating = false;

// speed & amount must be positive, change axis to control direction
IEnumerator DoRotation(float speed, float amount, Vector3 axis)
{
    isRotating = true;
    float rot = 0f;
    while (rot < amount)
    {
        yield return null;
        float delta = Mathf.Min(speed * Time.deltaTime, amount - rot);
        transform.RotateAround(target.transform.position, axis, delta);
        rot  = delta;
    }
    isRotating = false;
}

Then when you want to start rotating, start the coroutine if it isnt already rotating:

if (!isRotating)
{
    StartCoroutine(DoRotation(50f, 90f, Vector3.back));
}

It's slightly better form to save the Coroutine itself instead of using a flag. This lets you do stuff like stop the rotation at any point.

private Coroutine rotatingCoro;

// speed & amount must be positive, change axis to control direction
IEnumerator DoRotation(float speed, float amount, Vector3 axis)
{
    float rot = 0f;
    while (rot < amount)
    {
        yield return null;
        float delta = Mathf.Min(speed * Time.deltaTime, amount - rot);
        transform.RotateAround(target.transform.position, axis, delta);
        rot  = delta;
    }

    rotatingCoro = null;
}

// ...

if (rotatingCoro != null)
{
    rotatingCoro = StartCoroutine(DoRotation(50f, 90f, Vector3.back));
}

// ...

// call to stop rotating immediately
void StopRotating()
{
    if (rotatingCoro != null) 
    {
        StopCoroutine(rotatingCoro);
        rotatingCoro = null;
    }
}
  • Related