Now that we can think in terms of objects, let’s look at using an array to manage a large number of objects.
Arrays, as you already know, can hold any collections of any data type. Which means they can also hold a collection of objects!
If an array is just a collection of objects, we can address each array element as the object variable.
To create an array of objects, we simply need a loop in our setup()
function that will push, n number of objects into the array. This might look like;
let dudes = [];
let num_of_dudes = 20;
let bg_color;
function setup() {
createCanvas(windowWidth, windowHeight);
bg_color = color(34, 131, 157);
for (let i = 0; i < num_of_dudes; i++) {
dudes.push( new MarchingDude() );
}
}
Since the class handles all of the “nitty-gritty” during the construction of new objects, we simply need to use the new
keyword and pass the new object into the array.
As you will see in the code below, the class we are using for this example has three methods that need to be executed every frame. However, in the class definition, there is an additional method, called .frame()
. This method calls the other methods.
To call a method from within an object, use this dot notation! (i.e. this.someMethod()
);
In the class definition, the frame()
method looks like;
frame() {
this.feetAngle();
this.display();
this.move();
}
Then, in the sketch.js
file, the draw()
function simply needs to call the .frame()
method for every object. To do this, simply use a for loop to work through the array.
function draw() {
background(bg_color);
for (var i = 0; i < dudes.length; i++) {
dudes[i].frame();
}
}
The final code and example looks like;
[ Code Download ] | [ View on GitHub ] | [ Live Example ] |
The code from Shiffman’s example is below;
[ Code Download ] | [ View on GitHub ] | [ Live Example ] |