Search code examples
cameralibgdxrotation

How to get camera rotation in libGDX?


I want to get the rotation of the OrthograpicCamera in libGDX. I'm currently using this formula that I copied from another SOF post:

float camRotation = -(float)Math.atan2(cam.up.x, cam.up.y)*MathUtils.radiansToDegrees);

This returns -0.0 if I don't rotate.

If I rotate by 1 cam.rotate(1f); it camRotation prints -1.0 & if I rotate by -1 cam.rotate(-1f); camRotation prints 1.0

I'm confused by the math. What's the proper way to get camera rotation in libGDX?


Solution

  • I think it only the minus sign at the beginning of

    -(float)Math.atan2(cam.up.x, cam.up.y)*MathUtils.radiansToDegrees);
    

    that is causing your confusion, if you remove that it should work as you expect.

    atan2(b, a) gives you the angle between the positive x-axis and the point (a, b). Note calling it for (b, a) give the angle to the point (a, b) and not to point (b, a)

    In the example code you have atan2 is called with arguments cam.up.y and cam.up.x where cam.up is a unit-vector which indicates what is up.

    So in an unrotated camera the up-vector would be (0, 1) (it's actually a 3-dimensional vector but we can ignore the z-axis for now), if we plug that into the definition of atan2 is says that we should get the angle between positive-x (1, 0) and up (but with the arguments flipped) (1, 0), which is zero.

    So using atan2 to compare the up vector to the positive x-axis is a valid way of finding the rotation of the camera.