0

So I've been trying to create polygons with a certain amount of vertices, out of a circle, by calculating the points on this circle and then connect them all. The problem being : Processing won't connect the vertices together.

From the get go, the method I'm using isn't optimal, instead of calculating the points and then placing the vertices on those points, I'm using the rotate() function.

I know that there's a formula using sin() and cos() to calculate the points out of a circle, but I can't remember it.

Anyway, here's the code

translate(width/2,height/2);

ellipse(0,0,250,250);
let numPoints = 3;
beginShape();
for (let i = 0; i < numPoints; i ++){

    vertex(-250/2,0);
    ellipse(-250/2,0,10);
    rotate(TWO_PI/numPoints)
}
endShape();

Thanks for your help !

Enyak Stew
  • 156
  • 1
  • 9

1 Answers1

0

Check out this answer for a detailed explanation, otherwise:

polar to cartesian

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

for more info also see atan2

p5.js comes with the Regular Polygon example btw:

// example source: https://p5js.org/examples/form-regular-polygon.html

function setup() {
  createCanvas(720, 400);
}

function draw() {
  background(102);

  push();
  translate(width * 0.2, height * 0.5);
  rotate(frameCount / 200.0);
  polygon(0, 0, 82, 3);
  pop();

  push();
  translate(width * 0.5, height * 0.5);
  rotate(frameCount / 50.0);
  polygon(0, 0, 80, 20);
  pop();

  push();
  translate(width * 0.8, height * 0.5);
  rotate(frameCount / -100.0);
  polygon(0, 0, 70, 7);
  pop();
}

function polygon(x, y, radius, npoints) {
  let angle = TWO_PI / npoints;
  beginShape();
  for (let a = 0; a < TWO_PI; a += angle) {
    let sx = x + cos(a) * radius;
    let sy = y + sin(a) * radius;
    vertex(sx, sy);
  }
  endShape(CLOSE);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>
George Profenza
  • 50,687
  • 19
  • 144
  • 218