Search code examples
cgraphicspolygonprimitiveatan2

Draw a polygon in C


i need to draw a polygon of "n" sides given 2 points (the center and 1 of his vertex) just that i suck in math. I have been reading a lot and all this is what i have been able to figure it (i dont know if it is correct):

Ok, i take the distance between the 2 points (radius) with the theorem of Pythagoras:

sqrt(pow(abs(x - xc), 2) + pow(abs(y - yc), 2));

And the angle between this 2 points with atan2, like this:

atan2(abs(y - yc), abs(x - xc));

Where xc, yc is the center point and x, y is the only vertex know.

And with that data i do:

void polygon(int xc, int yc, int radius, double angle, int sides)
{
    int i;
    double ang = 360/sides; //Every vertex is about "ang" degrees from each other
    radian = 180/M_PI;
    int points_x[7]; //Here i store the calculated vertexs
    int points_y[7]; //Here i store the calculated vertexs

    /*Here i calculate the vertexs of the polygon*/
    for(i=0; i<sides; i++)
    {
        points_x[i] = xc + ceil(radius * cos(angle/radian));
        points_y[i] = yc + ceil(radius * sin(angle/radian));
        angle = angle+ang;
    }

    /*Here i draw the polygon with the know vertexs just calculated*/
    for(i=0; i<sides-1; i++)
        line(points_x[i], points_y[i], points_x[i+1], points_y[i+1]);
    line(points_y[i], points_x[i], points_x[0], points_y[0]);
}

The problem is that the program dont work correctly because it draw the lines not like a polygon.

Someone how know enough of math to give a hand? im working in this graphics primitives with C and turbo C.


Edit: i dont want to fill the polygon, just draw it.


Solution

  • Consider what 360/sides actually returns if sides is not a factor of 360 (this is integer division - see what 360/7 actually returns).

    There is no need to use degrees at all - use 2*Math_PI/(double)nsides and work throughout in radians.

    also you can omit the final line by using the modulus function (module nsides).

    If you have more than 7 sides you will not be able to store all the points. You don't need to store all the points if you are simply drawing the polygon rather than storing it - just the last point and the current one.