Hi,
First remember to format your code by pressing Ctrl+T
in the Processing IDE then use the </>
button to insert your code on the forum.
First of all, I think that you should always structure your code with the setup()
and draw()
functions provided by Processing even if you don’t want it to loop like this :
void setup(){
size(500, 500);
// Put your setup code here
}
void draw(){
// Put your drawing code here
// Stop the loop
noLoop();
}
Then it’s useful to program with functions. Functions are reusable pieces of code that you can call with custom parameters. Here it’s a typical example when drawing a polygon with a variable number of sides (9 in this case) :
void drawPolygon(int sides, float radius) {
// Your code here
}
Now you can call it in your draw()
function :
// 9 sided polygon with a radius of 100
drawPolygon(9, 100);
Then in your loop, you are using the number of steps so don’t say 9 directly but rather :
for (int i = 0; i <= steps; i++) { //... }
When drawing your lines, you added width / 2
and height / 2
each time but a common technique is to use the translate() function before you draw anything (remember to push and pop the transform matrix more info here) so you don’t need to add it each time :
pushMatrix();
translate(width / 2, height / 2);
// Draw your lines
popMatrix();
You want to draw a line for each side, so you need to compute the next position of the vertex of the polygon :
for (int i = 0; i < sides; i++) {
float angleRange = TWO_PI / sides;
float angle = i * angleRange;
float nextAngle = (i + 1) * angleRange;
line(cos(angle) * radius,
sin(angle) * radius,
cos(nextAngle) * radius,
sin(nextAngle) * radius);
}
So this is the final code :
void drawPolygon(int sides, int radius) {
// The size of each pieces
// Note that you can compute it outside the loop
float angleRange = TWO_PI / sides;
pushMatrix();
translate(width / 2, height / 2);
for (int i = 0; i < sides; i++) {
// First angle
float angle = i * angleRange;
// Next angle
float nextAngle = (i + 1) * angleRange;
line(cos(angle) * radius,
sin(angle) * radius,
cos(nextAngle) * radius,
sin(nextAngle) * radius);
}
popMatrix();
}
void setup() {
size(500, 500);
}
void draw() {
// Draw the 9 sided polygon
drawPolygon(9, 100);
// Stop the loop
noLoop();
}
Nice, now you have a reusable function where you can specify an arbitrary number of sides!!