Search code examples
processingp5.js

What is the math behind creation of a star in p5js


I was doing one of the examples code from the website p5js.org - https://p5js.org/examples/form-star.html. I understood all the code except the below lines.

function star(x, y, radius1, radius2, npoints) {
  let angle = TWO_PI / npoints;
  let halfAngle = angle / 2.0;
  beginShape();
  for (let a = 0; a < TWO_PI; a += angle) {
    let sx = x + cos(a) * radius2;
    let sy = y + sin(a) * radius2;
    vertex(sx, sy);
    sx = x + cos(a + halfAngle) * radius1;
    sy = y + sin(a + halfAngle) * radius1;
    vertex(sx, sy);
  }
  endShape(CLOSE);
}

What is the concept of taking two angles . I understand that this is using polar coordinates to cartesian coordinates mapping. But I am not able to visualize this in head that how this computation works. How the author come up with this logic in the code ?


Solution

  • The author is drawing lines. To do so, they need 2 points.

    To get the coordinates of these points, they "imagine" a circle because if the star is regular, every point should be at the same distance from the middle (hence drawing an imaginary circle around the middle point of the star). Like this:

    Imaginary circle

    Now, a circle is 360 degrees, or, in radians, 2 * PI. Like this:

    Radians

    Note that: zero radians is on the right. If you read counter clockwise, you get to 1/2 PI when you're on "top" of the circle, 1 * PI when you're on the left, 1,5 * PI on the bottom and 2 * PI once back on the right side.

    By dividing the circle by the amount of points the star has, the author can now use trigonometry to get the coordinates they need to draw the star:

    Trigonometry!

    That's the idea. Have fun!