Confusion with floats converted into ints during collision detection

Posted by TheBroodian on Game Development See other posts from Game Development or by TheBroodian
Published on 2012-10-09T22:20:06Z Indexed on 2012/10/10 3:54 UTC
Read the original article Hit count: 244

So in designing a 2D platformer, I decided that I should be using a Vector2 to track the world location of my world objects to retain some sub-pixel precision for slow-moving objects and other such subtle nuances, yet representing their bodies with Rectangles, because as far as collision detection and resolution is concerned, I don't need sub-pixel precision. I thought that the following line of thought would work smoothly...

Vector2 wrldLocation;
Point WorldLocation;
Rectangle collisionRectangle;

public void Update(GameTime gameTime)
{
     Vector2 moveAmount = velocity * (float)gameTime.ElapsedGameTime.TotalSeconds
     wrldLocation += moveAmount;
     WorldLocation = new Point((int)wrldLocation.X, (int)wrldLocation.Y);
     collisionRectangle = new Rectangle(WorldLocation.X, WorldLocation.Y, genericWidth, genericHeight);

}

and I guess in theory it sort of works, until I try to use it in conjunction with my collision detection, which works by using Rectangle.Offset() to project where collisionRectangle would supposedly end up after applying moveAmount to it, and if a collision is found, finding the intersection and subtracting the difference between the two intersecting sides to the given moveAmount, which would theoretically give a corrected moveAmount to apply to the object's world location that would prevent it from passing through walls and such. The issue here is that Rectangle.Offset() only accepts ints, and so I'm not really receiving an accurate adjustment to moveAmount for a Vector2.

If I leave out wrldLocation from my previous example, and just use WorldLocation to keep track of my object's location, everything works smoothly, but then obviously if my object is being given velocities less than 1 pixel per update, then the velocity value may as well be 0, which I feel further down the line I may regret.

Does anybody have any suggestions about how I might go about resolving this?

© Game Development or respective owner

Related posts about XNA

Related posts about 2d