Alex Rivera | Logout

How to draw a n sided regular polygon in cartesian coordinates?

Asked 2011-08-25T22:53:54.790
33

I have been trying to figure out how to write a simple program to compute the x,y points for creating a regular polygon of n sides. Can someone give me some code examples that don't use preexisting functions that draw polygons? I want to understand the process, which I assume is something like this:

  1. pick an angle to start from a radius and a center point
  2. somehow calculate the x,y position at that distance from the center(how?)
  3. divide 360 by the number of sides, move that distance and draw the next line from the first x,y point
  4. continue until the angle=360 divided by that number.

Assuming that my assumptions are correct, the main thing is to understand how to compute the x,y points.

Prefer answers in a visual basic (or even old style Microsoft/Atari/Commodore BASIC) or a human readable set of steps in English. If you have to answer with a math formula, do it in a computer language so I can read it, even in C or C++ I can figure it out, but I don't know how to read mathematical notation. The language I'm using is a Visual Basic-like language that has almost no graphics primitives other than line drawing.

Edit
Report

1 Answer

2

Here is a full c++ program that prints out the points of a regular polygon. In this case,p is the number of sides,r is the radius of the polygon and d is the direction or angle of the first point from the center. Maybe this will help.

//g++ ck.cpp -o ck && ./ck
#include <stdio.h>
#include <math.h>

int p=3; //number of sides
double r=1000,d=3/4.0;

int main()
{
 int i=0;
 double x,y,t;
 while(i<p)
 {
  t=2*M_PI*((double)i/p+d);
  x=cos(t)*r;
  y=sin(t)*r;
  printf("x%i:%f y%i:%f\n",i,x,i,y);
  i++;
 }
}
answered 2012-04-15T02:59:14.630

Your Answer