Shannon O'Leary
Shannon O'Leary

Reputation: 13

Finding closest circle from a point

I'm working on my world query methods for finding the closest entity from a point (for AI targeting). My entities are covered in bounding circles.

I have this:

var distanceX : Number = boundingCircle.position.x - startPosition.x;
var distanceY : Number = boundingCircle.position.y - startPosition.y;

var distance : Number = (distanceX * distanceX + distanceY * distanceY);

if (distance < lastDistance)
{
    // set this circle as the closest...
}

It doesn't take the radius of the bounding circle in to account though and that's giving me inaccurate results. Can I just subtract the radius squared from distance to get the distance to the edge of the bounding circle or do I need to calculate a more accurate distance with Math.sqrt?

Thanks!

Upvotes: 1

Views: 377

Answers (2)

maxim1000
maxim1000

Reputation: 6365

DistanceToCenter - radius == DistanceToCircle

but

DistanceToCenter^2 - radius^2 != DistanceToCircle^2

So you will not get distance by subtraction of squared values...

Upvotes: 0

aioobe
aioobe

Reputation: 420951

Can I just subtract the radius squared from distance to get the actual distance to the edge of the bounding circle

Yes, this should be perfectly fine.

If the distance to the enemy is Δ, and his bounding circle radius is r, then the distance to his bounding circle is Δ-r.

Upvotes: 1

Related Questions