Star

Star

The star() function created for this example is capable of drawing a wide range of different forms. Try placing different numbers into the star() function calls within draw() to explore.


void setup() {
  size(640, 360);
}

void draw() {
  background(102);
  
  pushMatrix();
  translate(width*0.2, height*0.5);
  rotate(frameCount / 200.0);
  star(0, 0, 5, 70, 3); 
  popMatrix();
  
  pushMatrix();
  translate(width*0.5, height*0.5);
  rotate(frameCount / 400.0);
  star(0, 0, 80, 100, 40); 
  popMatrix();
  
  pushMatrix();
  translate(width*0.8, height*0.5);
  rotate(frameCount / -100.0);
  star(0, 0, 30, 70, 5); 
  popMatrix();
}

void star(float x, float y, float radius1, float radius2, int npoints) {
  float angle = TWO_PI / npoints;
  float halfAngle = angle/2.0;
  beginShape();
  for (float a = 0; a < TWO_PI; a += angle) {
    float sx = x + cos(a) * radius2;
    float 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);
}

Functions Used

size()

Defines the dimension of the display window width and height in units of pixels

Learn More
vertex()

All shapes are constructed by connecting a series of vertices

Learn More
pushMatrix()

Pushes the current transformation matrix onto the matrix stack

Learn More
sin()

Calculates the sine of an angle

Learn More
popMatrix()

Pops the current transformation matrix off the matrix stack

Learn More
setup()

The setup() function is run once, when the program starts

Learn More
beginShape()

Using the beginShape() and endShape() functions allow creating more complex forms

Learn More
rotate()

Rotates the amount specified by the angle parameter

Learn More
cos()

Calculates the cosine of an angle

Learn More
translate()

Specifies an amount to displace objects within the display window

Learn More
draw()

Called directly after setup(), the draw() function continuously executes the lines of code contained inside its block until the program is stopped or noLoop() is called

Learn More
endShape()

The endShape() function is the companion to beginShape() and may only be called after beginShape()

Learn More
background()

The background() function sets the color used for the background of the Processing window

Learn More