# How to use for loops with transformations in processing?

So this is the code I wrote which I intend to draw n lines starting from a single point. Each separated by an angle of 2*PI / n.

int n;

void setup(){
size(displayWidth, displayHeight);
n = 7;
}
void draw(){
background(0);
push();
translate(displayWidth/2, displayHeight/2);
strokeWeight(4);

for (int i=0; i < n; i++){
stroke(random(255), random(255), random(255));
//println(i);
//println("theta is", i*(2*PI/n));
//println("theta in deg is", i*(2*PI/n)*180/PI);
rotate(i*(2*PI/n));
line(0, 0, 200 * 2, 0);
}
//noLoop();
pop();
}

void keyPressed(){
if (key == '='){
n++;
} else if (key == '-'){
n--;
if (n <= 0) n = 1;
}
}

It is wrong for some reason as it doesnâ€™t work for n=3,5,6,7,9,10...
I mean it doesnâ€™t work.

It is working only when n is 1,2,4,8,16,32... i.e. only 2 multiples.

I must be doing something wrong. Any help appreciated.

Use -, = keys to alter the spike count.

1 Like

@gotoloop can you help me?

Sorry, my trigonometry is almost nil.

So I replaced these lines with this

line(0, 0, 200 * 2 * cos(i*(2*PI/n)), 200 *2 * sin(i*(2*PI/n)));

i.e. normal polar coordinates (r*cos(a), r*sin(a))

And it works. Anyone knows why rotate didnâ€™t work?

Hello!

Please remember that rotate() in the line rotate(i*(2*PI/n)); adds up the angles

So you have to use push and pop inside the for-loop to avoid the adding up:

(using + and - here)

int n = 7;

void setup() {
size(displayWidth, displayHeight);
}

void draw() {
background(0);

strokeWeight(4);

for (int i=1; i <= n; i++) {

stroke(random(255), random(255), random(255));
pushMatrix();
translate(displayWidth/2, displayHeight/2);
//println(i);
//println("theta is", i*(2*PI/n));
//println("theta in deg is", i*(2*PI/n)*180/PI);
rotate(i*(2*PI/n));
line(0, 0, 200 * 2, 0);
popMatrix();
}// for
//noLoop();
fill(255);
text(n, 33, 33);
}

void keyPressed() {
if (key == '+') {
n++;
} else if (key == '-') {
n--;
if (n <= 0) n = 1;
}
}

OR

you use the fact that rotate() adds up the angles and then you just donâ€™t multiply by i

you just rotate a step further inside the for loop

Chrisir

int n = 7;

void setup() {
size(displayWidth, displayHeight);
}

void draw() {
background(0);
strokeWeight(4);

pushMatrix();
translate(displayWidth/2, displayHeight/2);

for (int i=1; i <= n; i++) {
stroke(random(255), random(255), random(255));
rotate(2*PI/n); // !!!!
line(0, 0, 200 * 2, 0);
}// for

popMatrix();

fill(255);
text(n, 33, 33);
}

void keyPressed() {
if (key == '+') {
n++;
} else if (key == '-') {
n--;
if (n <= 0) n = 1;
}
}
4 Likes

Thank you very much. Now I understand. I thought I was doing push and pop in the loop all this time.

1 Like