Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I've googled this using a lot of keyword combinations, but to my great surprise I could not find an algorithm for constructing a regular, n-sided polygon into a given circle, i.e., finding the coordinates for the n corner points. All I could find were instructions how to do it by physical compass and straightedge, or interactive browser plug-ins without source.

So where could I find such an algorithm?

share|improve this question
2  
Let me restore your faith in the Google. ;-) Fourth hit for "algorithm regular polygon": gamedev.net/topic/… "Then, using basic trigonometry, chose n points spaced equidistantly around the circumference of the circle (ie - if n is 3, chose 3 points on the circumference that are 120 degrees apart from one another)." Which is exactly what Kevin's code does. –  Eric May 24 '12 at 14:26
add comment

1 Answer 1

up vote 10 down vote accepted

With i going from 0 to n-1 inclusive:

pointX[i] = ( sin( i / n * 2 * PI ) * radius ) + xOffset;
pointY[i] = ( cos( i / n * 2 * PI ) * radius ) + yOffset;

Edit: As Lars Viklund mentioned in the comments, this is only safe in languages like javascript in which integer division returns a floating point number rather than a integer. In other languages you should first cast i to a float.

share|improve this answer
3  
Beware the trap of integral division in i/n in languages where dividing integers yields an integer. –  Lars Viklund May 24 '12 at 14:11
    
Aah a very good point, I'll add that caveat in the answer. –  Kevin van der Velden May 24 '12 at 14:24
    
This goes without saying, but you'll also want to guard against the case where n * 2 * PI == 0 or you'll have one unhappy polygon :(. –  Zack The Human May 25 '12 at 22:39
    
Barring weird overflows the only n with n * 2 * PI == 0 I can think of is 0, which as far as I know is undefined, same as i / 0. So no problem right? :) –  Kevin van der Velden May 26 '12 at 8:42
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.