1
votes

Currently, my game using some pixel detections. For exemple, for sprites, i retrieve the pixel of its position. When i move it, the position values have some decimals like :

thePixel = new vector(position.X, position.Y);
//thePixel = (52.2451, 635.2642)

so i have to Round These values

thePixel = new vector((float)Math.Round(position.X, 0), (float)Math.Round(position.Y, 0));
//thePixel = (52, 635)

I would like to know if there are some other ways to get perfect position (means, without decimal) without Rounding them. Is it maybe a moving method problem ?

Thx for reading, hope you can help.

1

1 Answers

3
votes

You can't really get around the need to round your values, but you can make it a lot nicer to code by using an extension method:

public static class Vector2Extensions
{
    public static Vector2 Floor(this Vector2 vector)
    {
        return new Vector2((float)Math.Floor(vector.X), (float)Math.Floor(vector.Y));
    }
}

(As you can see, personally I prefer Floor to Round. I also have one for Ceiling.)

Then you can just use it like this:

HandleCollision(position.Floor());

Of course, if you're doing per-pixel collision detection - your collision maths should probably be integer-based (not stored as float in a Vector2). You could use Point. Turns out I have an extension method for that too:

public static class Vector2Extensions
{
    public static Point AsXnaPoint(this Vector2 v)
    {
        return new Point((int)v.X, (int)v.Y);
    }
}

Then:

HandleCollision(position.AsXNAPoint());

Or possibly:

HandleCollision(position.Floor().AsXNAPoint());