Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Camera Rotation in Libgdx

I can't seem to find a way to tie the rotation of my ortho camera in libgdx (project with box2d) to the rotation of a box2d body. There is the method of cam.rotate(xy), giving it an impulse or acceleration, but I would like to set a definitive value, something like

cam.setAngle(player.body.getAngle());

How would I go about doing this? Do I have to write my own function? If so, then how? I want the rotation of the camera to always be the same as the player's...

Thank you!

like image 498
Jonas Avatar asked May 12 '13 15:05

Jonas


2 Answers

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

like image 69
Jonas Avatar answered Sep 21 '22 05:09

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)
like image 27
Ammar Tarajia Avatar answered Sep 18 '22 05:09

Ammar Tarajia