Change x position of an array of lines

hi Leute

could someone explain me why i cannot change the x position of an array of lines by pressing the arrow keyes?

the lines (looking like a sun) have all the same x position (0,0) translated to the middle of the canvas.

var linien=[];
var anzahl = 120;
 var angle;
 var step;
var x1 = 0;
var dia = 200;
function setup() {
  createCanvas(500, 500);
}

function createline(){
	  // Create object
  for (var i=0;i<anzahl;i++){
  linien[i] = new linie();
  }
}

function draw() {
  background(232,232,220);
  noStroke();
fill('rgba(255,.5)')
  ellipse(mouseX,mouseY,dia,dia);
  translate(width/2, height/2);
createline();
  for(var i=0;i<linien.length;i++){
  	
  linien[i].display();
  linien[i].move();
  
  }
 
}
// ein strahl class
this.linie = function() {
  this.x1 = 0;
  this.y1 = 0;
  this.x2 = 100;
  this.y2 = 100;
  this.speed = 1.5;
  this.angle = 0;
 this.step = TWO_PI/anzahl;
 
this.move = function(){
this.x2 += random(-this.speed,this.speed);
this.y2 += random(-this.speed,this.speed);
this.angle = this.angle;
}
  
    this.display = function() {
      strokeWeight(1);
      stroke(0);
      rotate(this.angle+this.step);
    line(this.x1, this.y1, this.x2, this.y2);
    //line(this.x1, this.y1, mouseX/2, mouseY/2);
   
  }
	
}
this.keyPressed = function(){
  if (keyCode === UP_ARROW) {
    anzahl += 1;
 	linien.length -= 1;
 	
    print(anzahl);
    
  } else if (keyCode === DOWN_ARROW) {
  	anzahl -= 1;
   linien.length -= 1;
  
    print(anzahl);
  }
  if (keyCode === LEFT_ARROW) {
    this.x1 -= 5;
    

print(x1);
  } else if (keyCode === RIGHT_ARROW) {
   this.x1 += 5;

 print(x1);
  }
  
}
1 Like

hi “Leut”

i think the biggest conflict in your program flow is

that you create the array again in every draw loop,
so it does not work changing parameters on the line, as they are over written anyhow.
only the changed globals like ‘anzahl’ would work.

but that leads to the next problem,
globals can change from a main

function keyPressed() {}

but not class local values the way you tried.

creating a keyPressed inside the class is tricky
and in the case of your array work only in the way that ALL elements
are changed…
not sure you wanted that.

i have something to show, but can not be called a solution…
https://editor.p5js.org/kll/sketches/4V4f0zOs8

1 Like