Calculating point on a circle's circumference from angle in C#?

x4000 picture x4000 · Mar 23, 2009 · Viewed 42.8k times · Source

I imagine that this is a simple question, but I'm getting some strange results with my current code and I don't have the math background to fully understand why. My goal is simple, as stated in the title: I just want to find the point at some distance and angle from a center point.

My current code:

Point centerPoint = new Point ( 0, 0 );
Point result      = new Point ( 0, 0 );
double angle      = 0.5; //between 0 and 2 * PI, angle is in radians
int distance      = 1000;

result.Y = centerPoint.Y + (int)Math.Round( distance * Math.Sin( angle ) );
result.X = centerPoint.X + (int)Math.Round( distance * Math.Cos( angle ) );

In general, this seems to work fairly reasonably, but I get problems at various spots, most notably when the angle corresponds to points in the negative x and y axis. Clearly I'm doing something wrong -- thoughts on what that is?

UPDATE: This was my mistake, this code works fine -- the few outliers that were not working were actually due to a bug in how the angle for 1.5PI was being calculated. I thought I had checked that well enough, but evidently had not. Thanks to everyone for their time, hopefully the working code above will prove helpful to someone else.

Answer

MartinStettner picture MartinStettner · Mar 23, 2009

You forgot to add the center point:

result.Y = (int)Math.Round( centerPoint.Y + distance * Math.Sin( angle ) );
result.X = (int)Math.Round( centerPoint.X + distance * Math.Cos( angle ) );

The rest should be ok... (what strange results were you getting? Can you give an exact input?)