Eloren
Eloren

Reputation: 323

How to use RotateAround with Time?

private float degrees = 90f;

&

transform.RotateAround(new Vector3(0f, 0f, 0f), new Vector3(0f, 0f, 1f), degrees)

So I want to rotate my gameObject for 2 seconds from 0 degrees to 90 degrees. What should I do? Thanks :)

Upvotes: 1

Views: 1236

Answers (1)

derHugo
derHugo

Reputation: 90580

Whenever you want something to happen smooth over time in Unity you usually use Time.deltaTime

The completion time in seconds since the last frame.

On this way you convert any "speed" parameter from "amount / frame" into a framerate-independent "amount / seconds".

Then as you want the rotation to take 2 seconds or in this case have a speed 45° / s you simply multiply/devide by the according factor

transform.RotateAround(Vector3.zero, Vector3.up, degrees / durationInSeconds * Time.deltaTime);

If you rather want to do the rotation about 90° for 2 seconds but than stop you should use a Coroutines

StartCoroutine(Rotate(90, 2));

// flag to avoid concurrent routines
private bool isRotating;

private IEnumerator Rotate(float degrees, float duration)
{
    if(isRotating) yield break;
    isRotating = true;

    var startRotation = transform.rotation;
    var targetRotation = transform.rotation * Quaternion.Euler(0, 0, degrees);

    // Iterate for the given duration while keeping track of the current time progress
    for(var passedTime = 0f; passedTime < duration; passedTime += Time.deltaTime)
    {
        // this will always be a linear value between 0 and 1
        var lerpFactor = passedTime / duration;
        //optionally you can add ease-in and ease-out
        //lerpFactor = Mathf.SmoothStep(0, 1, lerFactor);

        // This rotates linear 
        transform.rotation = Quaternion.Lerp(startRotation, targetRotation, lerpFactor);
        // OR This already rotates smoothed using a spherical interpolation
        transform.rotation = Quaternion.Slerp(startRotation, targetRotation, lerpFactor);

        // yield in a Coroutine reads like
        // pause here, render this frame and continue from here in the next frame
        yield return null;
    }

    // just to be sure
    transform.rotation = targetRotation;

    isRotating = false;
}

Upvotes: 2

Related Questions