[help] Problem with Intersects() or my code

I’ve been trying to do collision detection using the Intersects() function with two rectangles.

I’ve got a player and multiple enemy’s. When the player intersects with an enemy a bool var is set to true and the enemy is removed, the next time the player intersects with an enemy I wan’t some thing else to happen.

Here is the code:

private void HandleCollision()
		{
			bool hasBlock = false;

			List<int> bulletsToRemove = new List<int> ();
			List<int> enemysToRemove = new List<int> ();

			for (int i = 0; i < Enemys.Count; i++)
			{
				if ( hasBlock == false && Enemys [i].EnemyBounds.Intersects (Player.PlayerBounds))
				{
					enemysToRemove.Add (i);
					Bullets.Add (new BulletEntity(EnemyBox, Player.Position));
					hasBlock = true;
					Console.WriteLine ("has block == false");
				}
				if ( hasBlock == true && Enemys [i].EnemyBounds.Intersects (Player.PlayerBounds))
				{
					Console.WriteLine ("has block == true");
				}
			}
				
				
			for (int i = 0; i < bulletsToRemove.Count; ++i)
			{
				Bullets.RemoveAt (bulletsToRemove[i]);
				i++;
			}
			for (int i = 0; i < enemysToRemove.Count; i++)
			{
				Enemys.RemoveAt (enemysToRemove [i]);
				i++;
			}
		}

My problem is the every time the player intersects with the enemy the code after “if ( hasBlock == false && Enemys [i].EnemyBounds.Intersects (Player.PlayerBounds))” get executed. I can’t for the life of me figure out what I am doing wrong. I would love some help.

edit: In my mind when hasBlock is set to false the next enemy should pass through the player and not be removed.

I’m guessing the two if blocks are mutually exclusive? If so perhaps consider changing the second if statement to else if or even a continue after setting hasBlock = true. Also, is there any reason you’re incrementing i twice in the loop to remove enemies/bullets at the bottom?

The problem I believe is that hasBlock is declared inside the function - thus, every time the function is run, it’s re-initialized as false. Put it outside of the function (but still inside the class) and it should retain whatever value the function sets it to. Or perhaps put hasBlock in the Enemy class so that each enemy will have its own value?

Edit: Oops, this topic is 3 years old.

1 Like

Necromancer powers activate :stuck_out_tongue:

You must be playing too much the necromancer in Diablo2/3 :stuck_out_tongue_winking_eye: