Set Camera Rotation in Libgdx

After a good nights sleep I just woke up with the solution in mind! the function cam.angle(angle) obviously does set the angle to what you want (in degrees) - but you must only do it once and not in your update-loop, otherwise the camera just starts spinning. Which is obvious, but I just didn't get it.

the other problem is that the box2d body has "endless" degrees (i convert everything to degrees with *MathUtils.radiansToDegrees), so I had to constrain these to 0 to 359:

playerAngle = player.body.getAngle()*MathUtils.radiansToDegrees;

while(playerAngle<=0){
        playerAngle += 360;
    }
while(playerAngle>360){
        playerAngle -= 360;
    }

The camera's degrees go from -180 to 180, so you must also convert these to 0 to 359:

    camAngle = -getCameraCurrentXYAngle(camera) + 180;

The function "getCameraCurrentXYAngle(cam) is the following:

public float getCameraCurrentXYAngle(OrthographicCamera cam)
{
    return (float)Math.atan2(cam.up.x, cam.up.y)*MathUtils.radiansToDegrees;
}

And now in use this to update your cam to the rotation of your player:

    camera.rotate((camAngle-playerAngle)+180);

I hope this helps the person who upvoted my question;)

Cheers and have a productive day! Jonas


In Box2D, angles can be infinite as stated in the answer suggested. The method used to bound the angle however is quite inefficient. A more efficient solution would instead use modular arithmetic through the following snippet:

playerAngle = (player.body.getAngle() % 360) * MathUtils.radiansToDegrees()

Working out the camera's angle would be the next step, the solution provided above is adequate in this regard but could be condensed further into:

public float getCameraAngle(OrthographicCamera cam) {
    return ((float) -Math.atan2(cam.up.x, cam.up.y) * MathUtils.radiansToDegrees) + 180;
}

Now rotating the camera by the given angle is efficient for all values possible using the rotate() method:

camera.rotate((getCameraAngle(camera) - playerAngle) + 180)