1
\$\begingroup\$

Is there a formula to calculate world unit or pixels per unit values in LibGdx? Most of my objects fit into a 32x32 or 16x16 frame. When the objects are close to 32x32, and I use 1f as the size or 16x16 and use .5f things seem to work out fine. What I try to do is use this:

// Create viewport that is used to as the game size
static final float VIEWPORT_WIDTH = 15f;
static final float VIEWPORT_HEIGHT = 7f;

viewport = new FitViewport(VIEWPORT_WIDTH, VIEWPORT_HEIGHT);

// Scale sizes
final float UNIT_PIXEL = 0.03125f;  // 1 / 32
float newSize = 32f * UNIT_PIXEL;

Which seems to work for 32x32 or 16x16. But size problems seem to happen when you try to use that to calculate other widths or heights. Like if I try to use:

float newSize = 24f * UNIT_PIXEL;

Using this the bounding rectangle becomes much larger than the object.

\$\endgroup\$
  • \$\begingroup\$ Why do you cast like this? (float)(24 * UNIT_PIXEL)? This looks like it can cause some rounding issues. Instead do 24f * UNIT_PIXEL. \$\endgroup\$ – Charanor Apr 24 '17 at 10:13
  • \$\begingroup\$ Thanks for bringing that to my attention, it seems to have made a little difference, I'll have to do more testing. \$\endgroup\$ – user1572522 Apr 24 '17 at 16:04
  • 1
    \$\begingroup\$ Can you add what your resize looks like? Also what is the calculated size of your 24px images? It should be 0.75. \$\endgroup\$ – Charanor Apr 25 '17 at 15:03
0
\$\begingroup\$

The problems you're having is due to the ratio between viewport width and your images. Currently you're using 15 as a width value and 7 as a height value. This doesn't fit well into 32 or 16.

E.g.
32/15 = 2.13333 recurring 
16/15 = 1.06666 recurring
32/7  = 4.57142 etc
16/7  = 2.28571 etc

These recurring numbers are causing your conversion values to loose precision.

One way to fix this is to make your viewport width and height a Power of Two the same as your images. so 15 x 7 should become 16 x 8; This way when you want to convert back and forth you can use values without lots of decimal places.

E.g.
32/16 = 2
16/16 = 1
32/8  = 4
16/8  = 2
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.