How to fix the positions of lines (Math related)


(I am trying to do this with a n-sided shape)
but it is not working. The program works by having a position of the corner and giving a dir and r. How do I get the correct position? The current program only works for n = 6

Code
ArrayList<line> lines = new ArrayList<line>();
float v = 0, speed = 0.01, n = 6;
void setup() {
  size(600,600);
  float a = TWO_PI/n, cx = 300, cy = 300, nr = 200, nr2 = dist(cos(0)*nr,sin(0)*nr,cos(a)*nr,sin(a)*nr);
  for(int i = 0; i < n; i++) {
    float nx = cx+cos(a*i)*nr, ny = cy+sin(a*i)*nr;
    lines.add(new line(nx,ny,a*(i-1),-nr2));
  }
  //lines.add(new line(100,100,0,400));
  //lines.add(new line(500,100,PI/2,400));
  //lines.add(new line(500,500,PI,400));
  //lines.add(new line(100,500,PI*1.5,400));
  background(0);
} 
void draw() {
  for(int i = 0; i < lines.size(); i++) {
    lines.get(i).display();
  }
  noFill();
  beginShape();
  for(int i = 0; i < lines.size()+1; i++) {
    PVector vertexPos = lines.get(i%lines.size()).getPos(v);
    vertex(vertexPos.x,vertexPos.y);
  }
  endShape();
  v+=speed;
  if(v >= 1 || v<=0) { speed*=-1; background(0); }
}
class line {
  float x, y, dir, r;
  line(float x1_, float y1_, float dir_, float r_) {
    x = x1_;
    y = y1_;
    dir = dir_;
    r = r_;
  }
  void display() {
    stroke(255);
    float nx = x + cos(dir)*r, ny = y + sin(dir)*r;
    line(x, y, nx, ny);
  }
  PVector getPos(float v) {
    return new PVector(x + cos(dir)*r*v, y + sin(dir)*r*v);
  }
}

ArrayList<LineClass> lines = new ArrayList<LineClass>();
float n = 7;

void setup() {
  size(600, 600);
  background(0);

  float a = TWO_PI/n, 
    cx = 300, cy = 300, 
    nr = 200;

  for (int i = 0; i < n; i++) {
    float nx = cx+cos(a*i)*nr, ny = cy+sin(a*i)*nr;
    lines.add(new LineClass(nx, ny, 
      cx+cos(a*(i+1))*nr, ny = cy+sin(a*(i+1))*nr) );
  }
} 

void draw() {
  background(0);

  for (LineClass lc : lines) {
    lc.display();
  }
}

// ==========================================================================

class LineClass {

  float x1, y1, 
    x2, y2;

  LineClass(float x1_, float y1_, 
    float x2_, float y2_) {
    x1 = x1_;
    y1 = y1_;

    x2 = x2_;
    y2 = y2_;
  }

  void display() {
    stroke(255);
    line(x1, y1, x2, y2);
  }
  //
}//class
//

1 Like