04 May 2011

Author

Jan Vantomme

Tags

Processing Month, Day 4 - Stars

Today we’ll take a look at creating more complex shapes with Processing. We’re going to use beginShape() , endShape() and vertex() to draw a star to the screen. We’ll start by declaring some variables we need to calculate all points for the star: the inner radius, the outer radius, the number of spikes and an array to hold all the points. Note that the length of the array is 2 * numSpikes, as we need the same amount of points on the inner radius and on the outer radius of the star.

float innerRadius = 70;
float outerRadius = 180;
int numSpikes = 5;
PVector[] points = new PVector[ numSpikes * 2 ];

Next thing is calculating all points for the star. We need to make sure that we do this in the right order. All even points should be drawn on the outer radius, all odd points on the inner radius. To do this, we’ll use the modulo operator. If the remainder of i % 2 is zero, the points will be on the outer radius.

float angle = TWO_PI / points.length;
for ( int i = 0; i < points.length; i++ ) {
    float x, y;
    if ( i % 2 == 0 ) {
        x = cos( angle * i ) * outerRadius;
        y = sin( angle * i ) * outerRadius;
    } else {
        x = cos( angle * i ) * innerRadius;
        y = sin( angle * i ) * innerRadius;
    }
    points<i> = new PVector( x, y );
}

To draw the star to the screen, we will use the beginShape() and endShape() functions to create a real shape from the points we’ve calculated. We’ll use a for-loop between those two functions to iterate through our points array and make a vertex from each of the points. Make sure to use the CLOSE parameter for endShape(), otherwise the star won’t be a closed shape. You’ll see this when you draw the star with a stroke.

translate( width/2, height/2 );
beginShape();
for (int i = 0; i < points.length; i++) {
    vertex( points<i>.x, points<i>.y );
}
endShape(CLOSE);

Examples

Star

Star

Star

Star

OpenProcessing

I’ve been posting the examples on OpenProcessing. The sketch for today can be found over there: Stars, OpenProcessing.

Documentation

Download

Sketch for Processing Month, Day 4

Comments (2)

From:Raymond Rogers
Date:05.05.2011

Gravatar for Raymond Rogers

Your listing above doesn’t match the downloaded sketch book. In fact the listing doesn’t run. It stops at points<i> = new PVector( x, y );
Apparently <> should be []
Ray

Top · Permanent link to this comment

From:Jan Vantomme
Date:05.05.2011

Gravatar for Jan Vantomme

Thanks for noticing. I’m using Textile to format my blog posts and apparently it has some problems with code. I’ll try to fix it when I have the time.

Top · Permanent link to this comment

Commenting is closed for this article.
Commenting is not available in this channel entry.