Search code examples
if-statementnestednested-loops

Tower Defense - Checking enemy distance?


This question may be a duplicate of nested for loops/if statements, but please bear with me. I'm walking through the process of making a tower defense, and I will need to check if the enemy is within range of a tower. I could do some sort of physics circle, but I feel the best way is to check the distance of a tower for each enemy to see if it's within a radius. The thing is, if there's 500 'enemies' and 30 towers, that's 15,000 if statements per frame. Would this be performance heavy? The only way I know to make this any easier is to try these:

  • Only check every x frame (do the if loop 10 times a second instead of 100)
  • Do some guessing - nearby towers will use the same tower as theirs

Is there any other way to do any of this or am I on a good track?


Solution

  • Is it likely that all enemies will have moved each time you check? You could just recalculate each time an enemy moves, which towers are within the radius of that particular enemy, then update the list of enemies for just those towers that have either moved into the radius of the enemy, or out of it. You'd need to map each enemy to a list of towers, as well as each tower to a list of enemies.