1
\$\begingroup\$

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");
                }
                else 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.

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

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Everytime you call this fonction you set hasBlock to false.

Console.WriteLine ("has block == true"); will be executed only if the player collides with two enemies on the same frame.

The solution could be to use a static or a global variable.

\$\endgroup\$
1
  • \$\begingroup\$ facepalm do I ever feel stupid now. \$\endgroup\$
    – Nisroc
    Sep 22, 2014 at 7:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .