Impact

This forum is read only and just serves as an archive. If you have any questions, please post them on github.com/phoboslab/impact

1 decade ago by Bushstar

I have implemented proximity code for some entities and am not totally happy with it. Currently the entity is checking if the player entity 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 400x400 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 - this.pos.x > 200 && player.pos.x - this.pos.x < 200) 
  && (player.pos.y - this.pos.y > 200 && player.pos.y - this.pos.y < 200)) {
    this.playerRegistered();
}

1 decade ago by Graphikos

inCircle: function(radius) {
    var center = { x: (this.pos.x + this.size.x/2), y: (this.pos.y + this.size.y/2) };
    var pos = { x: ig.input.mouse.x + ig.game.screen.x, y: ig.input.mouse.y + ig.game.screen.y };
    return (Math.pow((pos.x - center.x),2) + Math.pow((pos.y - center.y),2) <= Math.pow(radius,2));
 }

// usage
if ( this.inCircle(40) ) {
     // mouse is within the circle
}

1 decade ago by Bushstar

Thanks for your response. I've found the same solution too. Simple math I'm told and now I know it. Knowledge is power!

((x1 - x0) * (x1 - x0)) + ((y1 - y0) * (y1 - y0)) < r2

I have the following solution which I think is very tidy.

inRange: function(p0, p1, r) {
    var dx = p0.x - p1.x;
    var dy = p0.y - p1.y;
    return (dx * dx + dy * dy) < (r * r);
}

Which I can use as...

if (this.inRange(player.pos, this.pos, this.sight))
Page 1 of 1
« first « previous next › last »