Area of a Circle

Started by
6 comments, last by psyjax 20 years, 2 months ago
Hey folks. This is a simple problem I ran in while working on my tile based game. The game bord is a 2D tileMap, sort of like a civilization board with cities, kingdoms etc. Anyway, each city structure has a circle inside of it defiend as such:
quote:struct CircleRec { int row; //row center int col; //col center int radius; };
The idea is I can use this circle to check the cities 'circle of influance'. Only problem is, I'm not quite sure how to check to see if any given point is within the circle. I need to be able to pass a row value and a col value to a function that will either return true or false. As so:
quote:int IsInCircle(Circle C, int row, int col);
I now this is a simple problem, folks have probably done this a million times. But I sleped thrugh triganometry :D Anyway, can anyone help me out? I would really apreciate it! EDIT: Used quote instead of source tags. Looks nicer. [edited by - psyjax on January 22, 2004 1:46:02 PM]
Advertisement
Point 1 is your city location. Point 2 is the location you''re checking. Do a distance...

d = sqrt((x1-x2)^2 + (y1-y2)^2)

Now, if d is less than your radius, then it''s inside the circle.
You''re only checking if the distance from the circle center to the specified point is less than the circle''s radius:
bool isInCircle( CircleRec &c, int row, int col ){  int x = c.col - col,      y = c.row - row;  return sqrt( x * x + y * y ) < radius;} 
A circle with centre (a, b) and radius r has equation:
(x*a)^2 +(y*b)^2 = r^2

Just plug in your x and y (row and column) and make sure the left side of the equation is less than or equal to the right side. In other words, satisfy the inquality:

(x*a)^2 +(y*b)^2 <= r^2

Note, for a little speed up you can avoid the square root by squaring your radius instead. Then compare that to the squared distance.

This works because |a| < |b| is equivalent to a^2 < b^2 for all a,b that are real numbers

-out
-out
Heh, lots of replies.
Hmmmm...

Well thanks alot! I really apreicate it!

I was thinking, I could avoid being too sqrt() heavy by simply precalculating all the points in the ''circle of influnce''.

I could have a 2D array inside the city structure, and simply fill the circle with TRUE values, and everything else with FALSE values. That way, I only need to scan the array. Would this be faster than using alot of sqrt()?
quote:Original post by BillPo
Note, for a little speed up you can avoid the square root by squaring your radius instead. Then compare that to the squared distance.

This works because |a| < |b| is equivalent to a^2 < b^2 for all a,b that are real numbers

-out


Actually. Your method, combined with the moderators suggestion, is perfect. Thank you all very much.

This topic is closed to new replies.

Advertisement