Domanda

I am currently making a top down shooter in xna. I have managed to work around this constant problem quite a few times in the project but now I am programming the gameplay and It is screwing with my collisions. I want the players life to go down by just 1 if they make contact with the enemy, but if the rectangles intersect it is called at the refresh rate of the software (or however it is done now that I think about it) so the players lives actually go down by a few dozen for the second of intersection. Is there a way to stop this?

example code which isn't working:

            if (playerRectangle.Intersects(enemyRectangle))
            {
                enemyAlive = false;
                playerLives--;
            }

I know this seems simple but it has been messing with my game all week. Thanks in advance for any help or advice!

È stato utile?

Soluzione

Change your condition to this:

(playerRectangle.Intersects(enemyRectangle) && enemyAlive)

and that should do the trick for you.

EDIT: as Zhafur pointed out, there is a simple optimization that can be done:

(enemyAlive && playerRectangle.Intersects(enemyRectangle))

I would point out that the Intersects method must check all 4 sides of the player's rectangle with all 4 sides of the enemy's rectangle. This would then make this simple call something like 16 smaller checks. If someone knows that figure for certain, please correct me if I am wrong. Personally I would do something like this:

float playerSize = 16f; // These are the _radius_ not the diameter.
float enemySize = 16f;

Then replace the Intersects method in the condition with a call to Vector2.Distance:

(enemyAlive && (playerSize + enemySize >= Vector2.Distance(playerLocation, enemyLocation)))

Where playerLocation and enemyLocation represent the center point of the player and enemy.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top