masthead

How do I know if a point is within the area of a circle?

UPDATE:

Wow, did I overthink this. No need for all the silly math, just take the distance from the point to the center of the circle, and compare that to the radius. Duh. For humility’s sake, the original post is below.

(Old post)

That is the question I asked myself a few days ago. And here is the answer (my apologies for the poor formatting, I need one of those code display plugins…):

/**
 * Determines whether or not a given point lies
   within a circle
 * @param circleX	The X value of the center
                        of the circle
 * @param circleY	The Y value of the center
                        of the circle
 * @param radius	The radius of the circle
 * @param ptX		The X value of the point
                        to be checked against the
                        circle
 * @param ptY		The Y value of the point
                        to be checked against the
                        circle
 */
public static function isWithinCircle( circleX:Number,
circleY:Number, radius:Number, ptX:Number, ptY:Number
):Boolean
{
	var theta:Number = Math.atan2( circleX - ptX,
circleY - ptY );
	var magnitude:Number = ( ptX - circleX ) /
Math.cos( theta );

	if( Math.abs( magnitude ) > radius )
		return false;
	else
		return true;
}

Here’s how it works: The formula to find the point (x, y) on the circumference of a circle with a center (a, b) is a = x + r cos ? and b = y + r sin ? where r is the radius of the circle and ? is the angle in radians from the center point at which the outer point lies.

Since I already know the location of both points and the radius of the circle, it’s pretty simple to fill in the gaps. I replaced r (for radius) with m (for magnitude) and then solved for m. The one last thing we need is the angle - I did a quick search and found that the angle between two points can be found using atan2 (not that I have any clue what that actually does…). That formula is ? = atan2(dX, dY).

Now when I plug in the points, I can check the value of m against the radius of the circle. If m < r, the point is inside the circle. Otherwise, it is outside. I’m no math expert so I can’t say 100% that this is the correct or the easiest/least processor intensive solution to this problem, but it has worked so far for me.

No Comments so far
Leave a comment



Leave a comment
Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

(required)

(required)