How to add object to an array properly in p5.js?

by cortez.connelly , in category: Javascript , 3 months ago

How to add object to an array properly in p5.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by ryleigh , 3 months ago

@cortez.connelly 

To add an object to an array properly in p5.js, you can use the push() method of the array. Here is an example of how to add an object to an array in p5.js:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
let objects = []; // create an empty array to store objects

function setup() {
  createCanvas(400, 400);
  
  let obj = { x: 100, y: 100 }; // create an object
  objects.push(obj); // add the object to the array
  
  console.log(objects); // check the array to see if the object was added successfully
}

function draw() {
  // draw the objects in the array
  background(220);
  for(let i = 0; i < objects.length; i++) {
    rect(objects[i].x, objects[i].y, 50, 50); // example drawing function
  }
}


In this example, we first create an empty array called objects. Then, we create an object called obj with properties x and y. We use the push() method to add the obj object to the objects array. Finally, in the draw() function, we loop through the objects array and draw the objects onto the canvas.


You can add as many objects as you want to the array by creating new objects and pushing them into the array using the push() method.