Search code examples
javalibgdx

Using world coordinates


I am currently using pixels as units for placing objects within my world, however this can get tedious because I only ever place objects every 16 pixels. For example, I would like to be able to place an object at position 2 and have the object rendered at the pixel position 32.

I was wondering if the best way to do this is simply having a pixel-to-unit variable and multiplying/dividing based on what I need to be doing with pixels or if there is a better way.


Solution

  • You shouldn't use constant a pixel-to-unit conversion, as this would lead to different behavior on different screen sizes/resolutions.
    Also don't forget about different aspect ratios, you also need to take care about them.
    The way you should solve this problem is using Viewports.
    Some of them support virtual screen sizes, which are what you are looking for. You can calculate everything in your virtual space, and Libgdx converts those things to pixels for you.
    They also take care about different aspect ratios in different ways.
    The FitViewport for example shows black borders, if the aspect ratio is not the same as the virtual one.
    The StretchViewport instead of showing black borders stretches the image to fit the screen.