Jump to content

Enemies IA that attack you if you are x pixels closer to them. [question]


eugenioclrc
 Share

Recommended Posts

Hello!

 

I am making a simple action game.

 

Just want the enemies in my game to have an action radio, so the wouldnt attack you unless you are x pixeles close to them.

 

I have noticed that i could itererate trought all the enemies, calculate the distance between the enemy and the player and filter them.

 

The question is, are there any other way to do this? wouldnt this algorithm be really hevy if there where lots of enemies in the game?

 

Link to comment
Share on other sites

There are probably some tweaks you can make, like maybe using Sprite.inCamera to determine if the sprite is being drawn.

However, the short answer is that math is pretty cheap. If you are just using Sprite.x there shouldn't be any problem.

 

Here's a helpful fiddle I made: http://jsfiddle.net/adamholdenyall/T457W/2/

On my machine it takes about 150 enemies to even make a 1ms hit. One million enemies takes about 715ms.

 

I also updated the fiddle to make it such that it tests that the X or the Y distance is greater than range before finding the actual distance. This cut down the time for one million enemies to 500-600 ms.

http://jsfiddle.net/adamholdenyall/T457W/3/

So yeah, you can improve it, but you risk diminishing returns for a pretty small problem.

Link to comment
Share on other sites

Another optimization trick that's used in games is to work with squared distances, which avoids the square root operation on each distance calculation.

 

So for example if you wanted to test if an object was within 20 pixels of the player, you'd test for this (pseudocode):

 

testDistSq >  (xDist * xDist + yDist * yDist)

 

where:

testDistSq = 20*20     (compute only once)

xDist = playerX - enemyX

yDist = playerY - enemyY

 

 

Instead of testing for this each time:

 

20 > sqrt(xDist*xDist + yDist*yDist)

 

 

This should be significantly faster when dealing with large numbers of comparisons, and you can always compute the actual distance after the fact for the in-range enemies if needed.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...