So I actually posted this in the C# section, but despite peoples best efforts, all all the help there, the problem is still not solved.
Background:
Im making a game in xna/c# (Who isnt these days). For collision detection, I though I would use rectangles and lists.
My thought process was:
1. Load collision map file
2. Parse file, where there is a 1, create a rectangle and add to list
3. In the player class, iterate through the list of rectangles (I called the list 'badTiles')
4. If the player intersects one of the rectangles, prevent them from moving, if not, allow them to move as normal.
The problem is, the player will only be prevented from moving into the last 'badTile' in the list. Why is this happening?
player class code:
private void TestCollResolve(Player player, Core core, Camera camera, Direction dir)
{
foreach (Rectangle badTile in core.badTiles)
{
if (futurePos.Intersects(badTile))
{
Console.WriteLine("Collision with bad tile: " + badTile.ToString());
// Players future position will intersect a bad tile, dont change players position vector.
if (dir == dirUp)
{
player.playerVel.Z = 0; // Change velocity vector of player and camera to 0.
camera.CameraVel.Z = 0;
}
else if (dir == dirDown)
{
player.playerVel.W = 0; // Change velocity vector of player and camera to 0.
camera.CameraVel.W = 0;
}
else if (dir == dirLeft)
{
player.playerVel.X = 0; // Change velocity vector of player and camera to 0.
camera.CameraVel.X = 0;
}
else if (dir == dirRight)
{
player.playerVel.Y = 0; // Change velocity vector of player and camera to 0.
camera.CameraVel.Y = 0;
}
}
else if (!futurePos.Intersects(badTile))
{
// Players future position will not intersect a bad tile, chenge players position vector.
if (dir == dirUp || dir == dirDown)
{
// Change players yVector to tmp yVector.
player.playerBounds.Y = futurePos.Y;
// Restore players velocity components to origional values.
player.playerVel.Z = 2;
player.playerVel.W = 2;
// Restore cameras velocity components to origional values.
camera.CameraVel.Z = 2;
camera.CameraVel.W = 2;
}
else if (dir == dirLeft || dir == dirRight)
{
// Change players xVector to tmp xVector.
player.playerBounds.X = futurePos.X;
// Restore players velocity components to origional values.
player.playerVel.X = 2;
player.playerVel.Y = 2;
// Restore cameras velocity components to origional values.
camera.CameraVel.X = 2;
camera.CameraVel.Y = 2;
}
}
}
}
Im completly stumped on this one! Ive already added in break points at the foreach statement, the if(futurePos.Intersects(core.badTile)) and even added breakpoints checking what arrow keys are being pressed. Everything appears to be working fine, it just dosent work?!