Sign in to follow this  
eugenioclrc

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

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?

 

Share this post


Link to post
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.

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.