I need to make a game with Windows Forms for school. My game consists of a user who has to go through a maze. I'm trying to prevent my user from walking straight through walls using collision detection, but I'm stuck due to the changing shape of the rectangles used to represent the walls. Here is the image of the game. This question may be similar to this one , however with my movement I think that it is completely different since I do not have a grid or graphic card.
As you can see, the walls are quite thick. Each wall is represented by C # Rectangle,, like the image of my player (a small yellow ghost). I know how to determine if a player crosses through these walls using the C # method IntersectsWith(Rectangle r), but I'm not quite sure how to use this information to handle the collision and STOP so that the player crosses the walls in general.
Here is what I tried:
This is my actual motion code. Since the game is constructed in WinForm, the movement is initiated by keyboard events, such as OnKeyPressedandOnKeyUp
public void Move(Direction dir)
{
HandleCollision();
if (dir == Direction.NORTH)
{
this.y -= moveSpeed;
}
if (dir == Direction.SOUTH)
{
this.y += moveSpeed;
}
if (dir == Direction.EAST)
{
this.x += moveSpeed;
}
if (dir == Direction.WEST)
{
this.x -= moveSpeed;
}
}
This is my collision method HandleCollision():
private void HandleCollision()
{
if (this.x <= 0)
{
this.x = 0;
}
if (this.x >= 748)
{
this.x = 748;
}
if (this.y <= 0)
{
this.y = 0;
}
if (this.y >= 405)
{
this.y = 405;
}
foreach (Rectangle wall in mazeWalls)
{
if (playerRectangle.IntersectsWith(wall))
{
if (player.X > wall.X) { player.X += wall.Width; }
else if (player.X < wall.X) { player.X -= wall.Width; }
else if (player.Y > wall.Y) { player.Y += wall.Height; }
else if (player.Y < wall.Y) { player.Y -= wall.Height; }
}
}
}
. , / , , , . , , if (playerRectangle.IntersectsWith(wall)) {?