Reputation: 4487
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, 400, 0);
}
//noLoop();
pop();
}
void keyPressed(){
if (key == '='){
n++;
} else if (key == '-'){
n--;
if (n <= 0) n = 1;
}
}
It's wrong for some reason as it doesn't work for n=3,5,6,7,9,10..
.
It's 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.
Whereas it is working if I do normal trigonometry.
i.e. by replacing
rotate(i*(2*PI/n));
line(0, 0, 400, 0);
by
line(0, 0, 400 * cos(i*(2*PI/n)), 400 * sin(i*(2*PI/n)));
Use -, =
keys to alter the spike count.
Upvotes: 1
Views: 292
Reputation: 858
Your problem is that you don't rotate the matrix the same amount for every of the n
arms.
You can fix your code by simply removing the i*
in your rotate command.
So
rotate(i*(2*PI/n));
line(0, 0, 400, 0);
sould be
rotate(2*PI/n);
line(0, 0, 400, 0);
If you want to work with i*
you have to push and pop a matrix every time you draw a line and not only at the beginning and on the end of draw()
:
push();
rotate(i*(2*PI/n));
line(0, 0, 400, 0);
pop();
Upvotes: 3
Reputation: 580
surround the rotate inside your for loop with push and pop, this way you reset the rotation each iteration, I tried it and its working here is the resulting code
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);
push();
rotate(i*(2.0*PI)/n);
line(0, 0, 400, 0);
pop();
}
pop();
}
void keyPressed(){
if (key == '='){
n++;
} else if (key == '-'){
n--;
if (n <= 0) n = 1;
}
}
Upvotes: 2