2

I have an enemy rectangle

public void Update(GameTime gameTime)
{
  enemyRectangle = new Rectangle((int)enemyPosition.X, (int)enemyPosition.Y, enemyTexture.Width, enemyTexture.Height);
 ...

I have a foreach loop, looping through a list of rectangles and a method that checks if these two rectangles have intersected which will return a boolean.

foreach (Bounds bounds in bounds.boundsList)
{
  if (bounds.EnemyWallIntersects(testEnemy.enemyRectangle, bounds.CurrentRectangle))
   {
     testEnemy.isEnemyCurrentlyColliding = true;
   }
   testEnemy.isEnemyCurrentlyColliding = false;
 }          

I am certain these rectangles should be intersecting but I have no clue what is happening now. I have used a breakpoint and the rectangle is meant to be intersecting with getting to the point where it has the same X and Y as the enemy rectangle.

This is the "EnemyWallIntersects" method.

 public bool EnemyWallIntersects(Rectangle rect1, Rectangle rect2)
 {
   if (rect1.Intersects(rect2))
   {
     return true;
   }
   else
     return false;
 }
Fred
  • 3,365
  • 4
  • 36
  • 57
sa1addd
  • 57
  • 5
  • Post what you see in breakpoint would help others to answer your question. – Louis Go Mar 18 '20 at 09:16
  • 1
    As a side note, you can simplify your `EnemyWallIntersects` method by eliminating the `if` statement and instead just do: `return rect1.Intersects(rect2);` In fact, you could eliminate that entire method and just use `if (testEnemy.Rectangle.Intersects(bounds.CurrentRectangle))` inside your `foreach`. – Chris Dunaway Mar 18 '20 at 15:00

1 Answers1

2

Your testEnemy.isEnemyCurrentlyColliding = false; happens right after setting testEnemy.isEnemyCurrentlyColliding = true;, without else statement, so it'll always be set to false.

I'll keep in mind that it's a foreach loop, so even if you put an else statement, the next item in the list would override the testEnemy.isEnemyCurrentlyColliding again. If you only need to check if one of them results in true, I recommend using break, which will end the current foreach loop.

So as example:

foreach (Bounds bounds in bounds.boundsList)
    {
        if (bounds.EnemyWallIntersects(testEnemy.enemyRectangle, bounds.CurrentRectangle))
        {
            testEnemy.isEnemyCurrentlyColliding = true;
            break;
        }
        testEnemy.isEnemyCurrentlyColliding = false;
    }         

The else statement wouldn't be necessary if you're using break, because that would end the foreach loop right where it stands.

Steven
  • 1,996
  • 3
  • 22
  • 33