Question

I must be the worst person on the planet when it comes to math because i can't figure out how to change this circle radius:

from math import *
posx, posy = 0,0
sides = 32
glBegin(GL_POLYGON)
for i in range(100):
    cosine=cos(i*2*pi/sides)+posx
    sine=sin(i*2*pi/sides)+posy
    glVertex2f(cosine,sine)

I'm not entirely sure how or why this becomes a circle because the *2 confuses me a bit. Note that this is done in Pyglet under Python2.6 calling OpenGL libraries.

Followed Example 4-1: http://fly.cc.fer.hr/~unreal/theredbook/chapter04.html

Clarification: This works, i'm interested in why and how to modify the radius.

Was it helpful?

Solution

This should do the trick :)

from math import *    
posx, posy = 0,0    
sides = 32    
radius = 1    
glBegin(GL_POLYGON)    
for i in range(100):    
    cosine= radius * cos(i*2*pi/sides) + posx    
    sine  = radius * sin(i*2*pi/sides) + posy    
    glVertex2f(cosine,sine)

But I would pick another names for variables. cosine and sine is not exactly what these variables are. And as far as I see, you son't need a loop from 1 to 100 (or from 0 to 99, I'm not too good at Python), you just need a loop from 1 to sides.

Explanation: When you calculate

x = cos (angle)
y = sin(angle) 

you get a point on a circle with radius = 1, and centre in the point (0; 0) (because sin^2(angle) + cos^2(angle) = 1).

If you want to change a radius to R, you simply multiply cos and sin by R.

x = R * cos (angle)
y = R * sin(angle) 

If you want to transfer the circle to another location (for example, you want the circle to have it's centre at (X_centre, Y_centre), you add X_centre and Y_xentre to x and y accordingly:

x = R * cos (angle) + X_centre
y = R * sin(angle)  + Y_centre

When you need to loop through N points (in your case N = sides) on your circle, you should change the angle on each iteration. All those angles should be equal and their sum should be 2 * pi. So each angle should be equal to 2 * pi/ N. And to get i-th angle you multiply this value by i: i * 2 * pi / N.

OTHER TIPS

math : P=pr^2=p*r*r= p*r*2 programming i*2*pi/sides
together : i = p i*2, *2=r^2 this should help you

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top