Processing Month, Day 1 - Connecting Points, Part 1
Posted on 2011-05-01 by Jan Vantomme
Tags:
processing, tutorial
In this first article, we'll take a look at how we can calculate points on the circumference of a circle and how we can connect them. We need to do this in a flexible way so we can draw images based on 6 points as wel as images based on 18 points.
Calculation
To calculate the x and y coordinates of these points, you'll need to know how many points to draw, and the radius of the circle. In this example, I'll start with 12 points.
int numPoints = 12;
float radius = 150;
The next thing to do is to calculate the angle between the points. A circle is 360 degrees or 2 π radians, so to know the angle between the points we need to divide 360 degrees with the number of points. I'll use radians in the example because the cos()
and sin()
functions expect a number in radians, not in degrees. Processing has a few constants for circles and half circles, so for 2 π, we can use the TWO_PI
constant.
float angle = TWO_PI / numPoints;
for (int i = 0; i < numPoints; i++) {
float x = cos( angle * i ) * radius;
float y = sin( angle * i ) * radius;
points[i] = new PVector( x, y );
}
I do the calculations in the setup() method and store them in a PVector array so I don't have calculate the x and y coordinates over and over again while drawing. By using a for-loop you can easily calculate the coordinates for each of the points: angle * i
will give you a different angle each time the block of code inside the loop are executed.
Drawing
To draw a line from each point to all other points on the circle, you'll need to use a nested for-loop to go through the array of points. The if statement is used to compare the i and j counters. If they are not equal, the computer will draw a line between the two points. If i and j are equal, they represent the same point, so you don't need to draw a line.
for (int i = 0; i < numPoints; i++) {
for (int j = 0; j < numPoints; j++) {
if ( j != i ) {
line( points[i].x, points[i].y, points[j].x, points[j].y );
}
}
}
The Results
Documentation
Here are some links to the Processing documentation for the functions I used. The might be handy if you need some extra information.