I am making a simple Pacman game using c# in Visual studio. I decided to make a rectangles of a maze in which the main character can walk. I have a rectangle which covers main character's bounds:
Rectangle _pacmanBound = new Rectangle(Left, Top, 28, 28);
Then I take the 4 points of this rectangle (top left, bottom left, top right and bottom right). I also have a List with rectangle areas in which pacman can walk:
map = new List<Rectangle>();
map.Add(new Rectangle(12, 375, 430, 28));
map.Add(new Rectangle(12, 403, 28, 97));
map.Add(new Rectangle(12, 470, 430, 28));
Now I want to check if all these 4 points belong to any of the rectangles in a list (so it indicates that the area is walkable):
foreach (Rectangle r in _maze.map)
{
if (r.Contains(_pacmanBound.X, _pacmanBound.Y))
{
topLeft = true;
}
else if (r.Contains(_pacmanBound.X, _pacmanBound.Y + _pacmanBound.Height))
{
bottomLeft = true;
}
else if (r.Contains(_pacmanBound.X + _pacmanBound.Width, _pacmanBound.Y))
{
topRight= true;
}
else if (r.Contains(_pacmanBound.X + _pacmanBound.Width, _pacmanBound.Y + _pacmanBound.Height))
{
bottomRight = true;
}
}
After loop the first one is true, second - false, third - false and fourth = false
To let you better understand, I add this picture:
Any help is appreciated.
Your problem is that you're using else
clause. So, if the first if
clause is true, the program will not check other if
clauses. You need to remove else
clause:
foreach (Rectangle r in _maze.map)
{
if (r.Contains(_pacmanBound.X, _pacmanBound.Y))
{
topLeft = true;
}
if (r.Contains(_pacmanBound.X, _pacmanBound.Y + _pacmanBound.Height))
{
bottomLeft = true;
}
if (r.Contains(_pacmanBound.X + _pacmanBound.Width, _pacmanBound.Y))
{
topRight= true;
}
if (r.Contains(_pacmanBound.X + _pacmanBound.Width, _pacmanBound.Y + _pacmanBound.Height))
{
bottomRight = true;
}
}
Also, you don't have to check each point of pacman rectangle. You can just check, if map rectangle contains pacman rectangle:
foreach (Rectangle r in _maze.map)
{
if (r.Contains(_pacmanBound))
{
isPacmanInsideMaze = true;
break;
}
}