Reputation: 311
I'm trying to make a class "star" with a method inside of it that, at given coordinates and size, draws a star. Something like rect() or ellipse() functions.
How can make it?
Upvotes: 2
Views: 5144
Reputation: 631
Old question, but still relevant.
The below function works well for me. It takes a value for the xy location, the number of points you want the star to have and the inner radius (center to valley) and outer radius (center to point).
It basically works the same as when you try to draw a circle manually by drawing a sequence of points revolving around a center position, but by switching between the inner and outer radius for every point, you end up with a star shape.
function star(x, y, num_points, inner_radius, outer_radius) {
const angle = TWO_PI / num_points; // angle between two points
const halfAngle = angle / 2.0; // angle between point and valley
beginShape();
for (let a = 0; a < TWO_PI; a += angle) {
let sx = x + cos(a) * outer_radius;
let sy = y + sin(a) * outer_radius;
vertex(sx, sy); // vertex at point of star
sx = x + cos(a + halfAngle) * inner_radius;
sy = y + sin(a + halfAngle) * inner_radius;
vertex(sx, sy); // vertex at valley
}
endShape(CLOSE);
}
Upvotes: 1
Reputation: 1
With the new update on p5 you can simply type star(coordinates)
and then make the star.
Upvotes: -2
Reputation: 42174
The best advice I can give you is to get out a piece of paper and a pencil. Draw out the points of a star, and label their X and Y coordinates.
Then you can use something like the line()
or beginShape()
function to draw that on the screen using code.
You can find more info in the P5.js reference.
Upvotes: 2