Jan-Fredrik Braseth
Jan-Fredrik Braseth

Reputation: 1

How to calculate angle for transform.RotateAround so the end result has a y==0

So I need to solve the following puzzle:

There is a 3D cube with rotation (34,90,23) (or some other random values). I want to rotate around the local y-axis until transform.position.y == 0. In the editor I can just drag-rotate on the y axis until I see 0 as a value in the transform, but how do I do that with code? (You cannot just set y=0, because all the values change when you rotate around the local y-axis)

I am thinking about using transform.RotateAround(transform.position, transform.up, angle), but I don't know how to correctly calculate angle so that after RotateAround() the transform.rotation.y == 0.

And just to specify, I don't want to code the dragging itself, just the result. The rotation should be instant.

Can anyone write a working code for this?

Upvotes: 0

Views: 446

Answers (1)

Kardux
Kardux

Reputation: 2157

I guess what you are looking for is an "animation" that will affect the transform.localEulerAngles.y value. To achieve this I'd recommend using a coroutine (you can find Unity tutorial here).

It would look like this:

private IEnumerator RotateAroundY(float rotationTime)
{
    float timer = 0.0f;
    Vector3 startLocalEulerAngles = transform.localEulerAngles;
    Vector3 deltaLocalEulerAngles = new Vector3(0.0f, Mathf.DeltaAngle(startLocalEulerAngles.y, 0.0f), 0.0f);

    while (timer < rotationTime)
    {
        timer += Time.deltaTime;
        transform.localEulerAngles = startLocalEulerAngles + deltaLocalEulerAngles * (timer / rotationTime);
        yield return new WaitForEndOfFrame();
    }

    transform.localEulerAngles = startLocalEulerAngles + deltaLocalEulerAngles;
}

And you can call it using StartCoroutine(RotateAroundY(4.0f));.

If you're getting into Unity I highly recommend you to familiarize with coroutines :)

EDIT :
Sorry about not noticing you didn't needed an animation: if you simply want to rotate around the local transform.up vector, you can change the transform.localEulerAngles.y value.

You can do it this way transform.localEulerAngles.y = new Vector3(transform.localEulerAngles.x, 0.0f, transform.localEulerAngles.z);

Hope this helps,

Upvotes: 0

Related Questions