# 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 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.

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.

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

##### Share on other sites

I don't know how fast it is, but game.physics.arcade.distanceToObject will return the distance in pixels between two game objects. Looping through on screen enemies in a group and then running that calculation wouldn't be too bad.

##### Share on other sites

Good catch on that codevinsky. Under the hood it's simply doing the same thing.

You can use distanceBetween to test between sprites and groups and distanceToXY for sprites to X,Y

http://docs.phaser.io/World.js_.html#sunlight-1-line-1568

##### Share on other sites

Thank you adamyall and thanks codevinsky!!!! You are great!

##### 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.

## 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.

×   Pasted as rich text.   Paste as plain text instead

Only 75 emoji are allowed.