# "Pixel-perfect" camera positioning in 2d game

I am writing a 2d game using LibGDX. The view to the game world is top-down. The game shows a grid of lines, which looks nice when the camera is at its initial position (0,0).

The problem is now that when I move (shift) the camera left/right/up/down this grid sometimes becomes a bit blurry, so the lines do not look perfectly sharp any more.

I assume this is because in these cases the grid lines are not exactly on screen pixels, but somewhere in between. Is this correct?

In any case: Are there any "best practices" how to address this problem (not necessarily LibGDX-specific)?

I assume this is because in these cases the grid lines are not exactly on screen pixels, but somewhere in between. Is this correct?

Yes, this is correct. The camera in LibGDX is based on a vector, which is made out of floats. When your camera is in between pixels (like at (1.2f, 63.5f)), then you will start to see that blur you mention because the rendering engine will try to draw in between pixels and approximate the colors.

The simplest way to deal with that is to the position of the camera as an integer.

camera.x = (int) camera.x;
camera.y = (int) camera.y;

The best way to do this would be directly when you position your camera. If you move your camera with a player, for example, then the code would look like this:

camera.x = (int) (player.x + xOffset);
camera.y = (int) (player.y + yOffset);
• That makes sense, thanks for your quick reply. There is one more issue (in my case) though: I am using different world space coordinates than screen space coordinates. So I cannot directly cast to int, that makes my camera "jump" around. Is there an easy way to achieve your logic even in this case? Jul 22, 2014 at 19:08
• @Matthias Just make sure that the screen space coordinates are good when you make your conversions. Else than that, you cannot really predict that a given world space coordinate will be converted to a integer screen coordinate. Your best bet would be to multiply and divide by your factor. Ex: camera.x = ((int) player.x * factor) / factor; Jul 22, 2014 at 19:11
• Ohh that is great, thank you so much! This does exactly what I wanted :) Jul 22, 2014 at 19:20
• @AlexandreDesbiens Isn't the camera position measured in any arbitrary unit, so that just casting them to int might cause the camera to become more jittery than necessary? Or am I misunderstanding something? Aug 20, 2016 at 15:29