"sprite" is the player object, velocity is a Vec2 that tracks movement (is set to -1, 1, or 0 at any given time), each sprite in "sprites" is a wall of the same size as the player (everyone is a block for testing purposes).
if (velocity != Vec2.Zero)
{
Vec2 oldPos = sprite.Position;
sprite.Position = sprite.Position + velocity;
foreach (Sprite s in sprites.Except(new List<Sprite> { sprite }))
{
if (sprite.BoundingBox.Intersects(s.BoundingBox))
sprite.Position = new Vec2(oldPos.X, sprite.Position.Y);
if (sprite.BoundingBox.Intersects(s.BoundingBox))
sprite.Position = new Vec2(sprite.Position.X, oldPos.Y);
}
velocity = Vec2.Zero;
}
So, this actually works quite well - except for some reason it only works in one direction. Collisions work in both, but when sliding against a wall by holding two direction keys it only works sliding along the Y axis.
The bounding box for "sprite" is updated whenever the "Position" variable is written to via an accessor, so the bounding box is always up to date. The walls do not move, so theirs are also up to date.
At first glance, it seemed that there were a few obvious spots to check - I am modifying the bounding box for the second check, and at the time I hadn't been doing it automatically, so I tried disabling that. Doing so broke the working parts, so it wasn't that. I get no change in behavior when I add "else" to the second if statement, confirming that the first block always runs and the second block never does. If I flip them around, the other axis works instead.
I tried separating them into two foreach loops (just to see) and the behavior still remained the same. I'm kinda confused as to why none of these changes produced any hints as to the issue - it's likely something I'm overlooking, so I was hoping someone else would see.
If you need me to post any other code, just ask.
I was trying to do this in 3D and had a very bad time, so I figured I'd make a 2D version of my engine and get things sorted there before moving the collision back into 3D, heh..