1 decade ago by monkeyArms
Working on a top view RPG game, and I needed to find the closest entity the player was interacting with, taking the entity size into account. I'm sure there is an easier and simpler formula for this, but this works well for calculating the (shortest) distance from an entity's bounding box to another entity's midpoint (in this case, my player). I added this to my entities' base class:
distanceFromBoundingBoxToPoint: function( other ) { var p = { x: (other.pos.x + other.size.x/2), y: (other.pos.y + other.size.y/2) }, minX = this.pos.x, maxX = (this.pos.x + this.size.x), minY = this.pos.y, maxY = (this.pos.y + this.size.y), distSquared = 0; if (p.x > maxX) { distSquared += (p.x - maxX) * (p.x - maxX); } else if (p.x < minX) { distSquared += (minX - p.x) * (minX - p.x); } if (p.y > maxY) { distSquared += (p.y - maxY) * (p.y - maxY); } else if (p.y < minY) { distSquared += (minY - p.y) * (minY - p.y); } return Math.sqrt(distSquared); }