Make object array move as one unit

I am fairly new to P5.js and am trying to make an entity of lines move around the screen and rotate (like a twirling motion). I have the array of lines created but I can’t figure out how to make a statement that will apply to all of them as one unit. Also, as a side note, I have set the x1, x2, y1, y2 to loop and increase or decrease to create movement but as the program runs, the lines grow apart (as they keep adding which expands the location parameters). Is there a way to set a boundary? I attempted to set a boundary (commented out in the move section) but it didn’t work. I’m afraid that with my limited knowledge so far, I don’t know of any solutions, but I would love to learn.

My code so far:

let bubbles = [];

function setup() {
  createCanvas(600, 600, WEBGL);
  for (let i = 0; i < 30; i++) {
    bubbles[i] = new Bubble();
  }
}

function draw() {

  background(255, 255, 255, bc);

  for (i = 0; i < bubbles.length; i++) {
    bubbles[i].display();
    bubbles[i].move();
  } 
}

class Bubble {
  constructor() {
    this.x1 = random(-150, -160);
    this.y1 = random(50, 100);
    this.x2 = random(-135, -175);
    this.y2 = 150;
    this.speed = 1;
  }


  display() {

    let r = random(100, 255);
    let g = random(0, 50);
    let b = random(0, 50);
    stroke(0);
    line(this.x1, this.y1, this.x2, this.y2);

  }

  move() {
    // if (this.x1<-150 && this.x1>-160){
    this.x1 += random(-this.speed, this.speed);
    // }
    //if (this.y1<100 && this.y1>50){
    this.y1 += random(-this.speed, this.speed);
    // }
    //if (this.x2<-135 && this.x2>-175){
    this.x2 += random(-this.speed, this.speed);
    // }
    // if (this.y2>150 && this.y2<150){
    this.y2 += random(-this.speed, this.speed);
    //  }

  }

}
1 Like

please format your code posting by pasting it into the

</> code button

of the editor header menu ( context name: Preformatted text )
it looks like
```
type or paste code here
```

also can use the ``` manually above and below your code.

thank you.


also when using p5.js
it might be better just to link to your online editor project / or MVCE
https://editor.p5js.org/kll/sketches/9xCZ14SWH

you draw line X Y only,
but use WEBGL renderer ( for 3D )

i show you there how to use constrain()
but there might be other way.

but the real question might be WHY

i think that is a tricky statistical question behind it, when you change randomly
the 4 parameters of a line, it can walk anywhere, can grow longer or shorter…
so limiting must not only be in X/Y canvas,
possibly also limit min max length!

and there i recommend to change all that code to PVector


possibly now want position the whole array ( of objects ) in 3D space
use like

translate(x,y,z);

https://p5js.org/reference/#/p5/translate

2 Likes