I am writing a program in which I need to draw polygons of an arbitrary number of sides, each one being translated by a given formula which changes dynamically. There is some rather interesting mathematics involved but I am stuck on this probelm.
How can I calculate the coordinates of the vertices of a regular polygon (one in which all angles are equal), given only the number of sides, and ideally (but not neccessarily) having the origin at the centre?
For example: a hexagon might have the following points (all are float
s):
( 1.5 , 0.5 *Math.Sqrt(3) ) ( 0 , 1 *Math.Sqrt(3) ) (-1.5 , 0.5 *Math.Sqrt(3) ) (-1.5 , -0.5 *Math.Sqrt(3) ) ( 0 , -1 *Math.Sqrt(3) ) ( 1.5 , -0.5 *Math.Sqrt(3) )
My method looks like this:
void InitPolygonVertexCoords(RegularPolygon poly)
and the coordinates need to be added to this (or something similar, like a list):
Point[] _polygonVertexPoints;
I'm interested mainly in the algorithm here but examples in C# would be useful. I don't even know where to start. How should I implement it? Is it even possible?!
Thank you.
The simple method is: Let's take N-gone(number of sides) and length of side L. The angle will be T = 360/N. Let's say one vertices is located on origin. Show activity on this post.
It is easiest to find the coordinates of A if you think of the hexagon as 6 equilateral triangles. Each side of these triangles are of length r. Since the y axis creates a 30-60-90 triangle where A is one of the vertices, it is pretty easy to find the remaining sides of the triangle.
for (i = 0; i < n; i++) { printf("%f %f\n",r * Math.cos(2 * Math.PI * i / n), r * Math.sin(2 * Math.PI * i / n)); }
where r
is the radius of the circumsribing circle. Sorry for the wrong language No Habla C#.
Basically the angle between any two vertices is 2 pi / n and all the vertices are at distance r from the origin.
EDIT: If you want to have the center somewher other than the origin, say at (x,y)
for (i = 0; i < n; i++) { printf("%f %f\n",x + r * Math.cos(2 * Math.PI * i / n), y + r * Math.sin(2 * Math.PI * i / n)); }
The number of points equals the number of sides.
The angle you need is angle = 2 * pi / numPoints
.
Then starting vertically above the origin with the size of the polygon being given by radius
:
for (int i = 0; i < numPoints; i++) { x = centreX + radius * sin(i * angle); y = centreY + radius * cos(i * angle); }
If your centre is the origin then simply ignore the centreX
and centreY
terms as they'll be 0,0.
Swapping the cos
and sin
over will point the first point horizontally to the right of the origin.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With