I am trying to implement movement & collision the simplest way possible.
public void MovePlayer()
{
KeyboardState keyState = Keyboard.GetState();
Vector2 checkVec = location; //get current location
if (keyState.IsKeyDown(Keys.Left))
{
//Check what the next position would be
Rectangle checkRect = new Rectangle((int)(checkVec.X -= speed), (int)location.Y, texture.Width, texture.Height);
//Check if the next position would collide with any obstacles
bool collides = CheckCollision(checkRect);
//If it does not collide move..
if (!collides)
{
location.X -= speed;
}
}
if (keyState.IsKeyDown(Keys.Right))
{
Rectangle checkRect = new Rectangle((int)(checkVec.X += speed), (int)checkVec.Y, texture.Width, texture.Height);
bool collides = CheckCollision(checkRect);
if (!collides)
{
location.X += speed;
}
}
if (keyState.IsKeyDown(Keys.Up))
{
Rectangle checkRect = new Rectangle((int)checkVec.X, (int)(checkVec.Y -= speed), texture.Width, texture.Height);
bool collides = CheckCollision(checkRect);
if (!collides)
{
location.Y -= speed;
}
}
if (keyState.IsKeyDown(Keys.Down))
{
Rectangle checkRect = new Rectangle((int)checkVec.X, (int)(checkVec.Y += speed), texture.Width, texture.Height);
bool collides = CheckCollision(checkRect);
if (!collides)
{
location.Y += speed;
}
}
}
Here ist the CheckCollision() method:
private bool CheckCollision(Rectangle checkRect)
{
bool collides = false;
foreach (Tile t in blockedTiles)
{
if (t.rectBounds.Intersects(checkRect))
{
return true;
}
else
{
}
}
return collides;
}
So my problem is that due to the order in which I am checking button input when I get a collision from up or down everything works fine. But when it is collision from left or right the code does not recognize if I am simulatneously moving up or down, so in this case the Textture freezes as long as I provoke left or right collision.
Any ideas how to fix this?