rotate transformation doesn't work in processing for loop

Phani Rithvij :

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.

YOUSFI Mohamed Walid :

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;
  } 
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=310699&siteId=1