calculate coordinates of a polygon using radius and centerpoint

I am trying to calculate the coordinates of a polygon, coding it out isn't really a problem, its just my maths is quite bad but slowly learning.

I need to calculate the coordinates based on the center point and radius. e.g. centerX = 40, centerY = 40, radius = 8, sides = 5, i = n 0 - 5

This is what I have so far. int x, y; int sides = 5; int angle = 0;

for (size_t i = 0; i < sides; i++)
    x = round(centerX + radius * cos(2* PI * i / sides));
    y = round(centerY + radius * sin(2* PI * i / sides));
    points.push_back(point(x, y));

This does give me a nice polygon (kinda) when i plot the points on an online generator.

However, it is slightly rotated and i am not sure how to solve this, ideally i would like a flat line at the bottom.

So my questions are:

  1. Is my formula for x/y correct? can it be improved?
  2. how do i add rotation? for example 20 degrees

thank you for your help.


Rotation is a matrix operation. In 2D it's [[cos(a),-sin(a)],[sin(a),cos(a)]] applied to each point (x,y) like so (I don't know your language):

 xnew= cos(a)* x - sin(a)* y; 
 ynew= sin(a)* x + cos(a)* y; 

See e.g. Rotation_(mathematics)#Two_dimensions on Wikipedia. Note that the angle a is in radians, so you might need to multiply by pi/180 if your input is in degrees.

Assuming that you are coding in C++, I guess that what you are looking for is something like this:

for (size_t i = 0; i < sides; i++)
    double angle = M_PI / 2 + 2 * M_PI * i / sides;
    int x = round(centerX + radius * cos(angle));
    int y = round(centerY + radius * sin(angle));
    points.push_back(point(x, y));

Even if you choose to use integers to represent x,y coordinates it's better to use a double for the angle, which is in radians. I simply added Pi/2 to your formula to rotate the poligon 90° counter clock wise.

Need Your Help

AngularJS Factory Parameter

angularjs angularjs-factory

I'm trying to send a parameter to an angularjs service. Here is my service code :

How to find the days between dates using my code?

java sql date

Below is my code which checks the date which is stored in database with the current system date and calculates the days and if that days is lesser than the 180 days it will print something else print