[LibGDX] OrthographicCamera position issue

Hi!

I’m trying to make my camera not leave the map’s borders but it is not working and I don’t know why.
This is just a quick test to show you the code and the problem.


if(p1.getRealPosition().x - (Gdx.graphics.getWidth() * ZOOM / 2) <= 0){
	cam.position.x = cam.viewportWidth * cam.zoom / 2;
	cam.position.y = p1.getRealPosition().y;
}
else{
	cam.position.set(p1.getRealPosition(), 0);
}

if(p1.getB2DPosition().x - (Gdx.graphics.getWidth() * ZOOM / 2 / PPM) <= 0){
	b2dCam.position.x = Gdx.graphics.getWidth() * ZOOM / 2 / PPM;
	b2dCam.position.y = p1.getB2DPosition().y;
}
else{
	b2dCam.position.set(p1.getB2DPosition(), 0);
}

I’m using “cam” for most drawing nad “b2dCam” is only used for Box2D debug render. The wierd thing is that this code works perfectly with the b2dCam but it doesn’t with the normal cam.

Here is how it looks (and should look) with box2d

Here is the same picture same position with the normal camera. As you can see its off by far, it doesnt even show the player.

Could anyone please help me explain what causes this behaviour?

There is probably nothing wrong with the camera, are you scaling down your sprites to world coordinates and drawing using the b2dcam?

I’m using the normal cam’s projection matrix for everything expect the Box2D debug draw.

That is your problem then.

You should be using your Box2D camera to draw your sprites as well. Think about it, say you have a camera like so:


Camera b2dCam = new Camera(16, 9);

This creates a new camera that is 16 units by 9 units, now say you create a body with a fixture like so:

Psuedo


// X and Y are position, 0.5f, 0.5f is width/height. Fixtures take half width/height.
EnemySquare enemy = new EnemySqaure(x, y, 0.5f, 0.5f);

We now have an enemy that is 1x1 units.

Now lets create another camera to draw the sprites:

Camera someOtherCam = new Camera(800, 600);

Now draw the enemy with that camera, what problem do we get?


batch.setProjectionMatrix(someOtherCam.combined);
batch.begin();
enemy.draw();
batch.end();

Well first off, we have created an enemy that is 1x1, yet we are drawing a sprite that is iunno, 200x200 in pixels. That simply won’t work, instead we want to simulate and draw the world in box2d coordinates.

So use the b2d cam for drawing the sprites and make sure you scale them down before doing so.

I personally like to setup my camera manually like I did above, with some sort of 16:9 resolution (in this case it was 16x9). Then I do some sort of scaling factor, such as:

float scale = 1f/100f;

I can then use this to scale down pretty much everything, so you can first scale down the sprites and then use the half width/height of the sprites to create your fixture. Doing this will get you an exact screen to world sized version of your sprite, as in even although the window in photoshop is 1920x1080, and your window in your game is 16x9; the sprite will be the same physical size.