## Monday, 23 January 2012

### Circles

Circles are used for many things in 2D games. Not only for things that are inherently circular (wheels, balls) but for many effects and to describe many situations. For example the range of a gun is often a circle, or at least circular.

A circle is specified by three numbers: the coordinates of its centre and its radius. Often the coordinates are those of another object, such as the position of a gun. The radius is then the range or maximum distance it can shoot. But for clarity a separate class can be used, e.g.

class Circle {
var fX:Number; // x coordinate
var fY:Number; // y coordinate
function Circle(_x:Number, _y:Number, _r:Number) {
fX = _x;
fY = _y;
fR = _r;
}
}

To check whether something is inside a circle is straightforward. Simply compare the distance of the object from the centre of the circle with the radius, using Pythagoras's theorem. As a (member) function that is

function contains(x:Number, y:Number):Boolean {
var dX:Number = x - fX;
var dY:Number = y - fY;
return (dX * dX + dY * dY) < fR * fR;
}

It is almost as simple to check whether two circles intersect:

function intersects(toIntersect:Circle):Boolean {
var dX:Number = toIntersect.fX - fX;
var dY:Number = toIntersect.fY - fY;
var rSum:Number = toIntersect.fR + fR;
return (dX * dX + dY * dY) < rSum * rSum;
}