MonoGame - Unit Convertion

469 Views Asked by At

I want to use my own Unit"system". Something like 1 Pixel is equals to 0.01 Units.

Now when I want to draw something with my own Unitsystem, I always have to multiply/divide the value by 100. I've found some answers that mentioned to use matrix in SpriteBatch.Begin, but I dont know how.

Could someone help me^^?

2

There are 2 best solutions below

3
On

Spritebatch.Begin()´s last parameter can be a transform matrix.

TransformMatrix = Matrix.CreateScale(0.01);
spriteBatch.Begin(SpriteSortMode.Immediate, null, null, null, null, null, TransformMatrix);
0
On

Farseer Physics provides a ConvertUnits class for this kind of thing. From memory the methods you're interested in are ToSimUnits and ToDisplayUnits. The Farseer documentation describes it like this:

// 1 meter = 64 pixels
ConvertUnits.SetDisplayUnitToSimUnitRatio(64f);

// If you object is 512 pixels wide and 128 pixels high:
float width = ConvertUnits.ToSimUnits(512f) // 8 meters
float height = ConvertUnits.ToSimUnits(128f) // 2 meters

So the rules are:

  1. Whenever you need to input pixels to the engine, you need to convert the number to meters first.
  2. Whenever you take a value from the engine, and draw it on the screen, you need to convert it to pixels first.

If you follow those simple rules, you will have a stable physics simulation.

On a related topic, you should look into resolution independence.