I’m working on a HTML5 game and have what I think is a math problem. The player and enemy objects have a pos.x and pos.y value indicating where they are on the screen. I have implemented proximity check code for some enemies and am not totally happy with it. Currently the enemy is checking if the player is within a certain distance from it, 200 or -200 on the x and y axis. What this means is that the entity is scanning a 400×400 square around itself.
I would like to make this a circle with a radius of 200 instead. My code as it stands.
if ((player.pos.x - enemy.pos.x > 200 && player.pos.x - enemy.pos.x < 200)
&& (player.pos.y - enemy.pos.y > 200 && player.pos.y - enemy.pos.y < 200)) {
//Do something...
}
Here’s my game if you want to check it out. Proximity enemies are on the second and currently last level 🙂
It’s very basic math.
Check that (x1 – x0)2 + (y1 – y0)2 < r2
Call it like so:
You can supply a third optional argument to change the detection radius.