4. Modularity: Objects, Arrays, and Classes
As sketches become more complex, you'll need ways to manage multiple similar elements efficiently. Objects, arrays, and classes provide powerful tools for this.
4.1. Using Objects to Group Data
An object can store related data (properties) and actions (methods) for a single entity, like a "ball".
let ball = {
x: 100,
y: 100,
diameter: 50,
speedX: 3,
speedY: 2,
display: function() {
ellipse(this.x, this.y, this.diameter, this.diameter);
},
move: function() {
this.x += this.speedX;
this.y += this.speedY;
if (this.x > width - this.diameter/2 || this.x < this.diameter/2) {
this.speedX *= -1;
}
if (this.y > height - this.diameter/2 || this.y < this.diameter/2) {
this.speedY *= -1;
}
}
};
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
ball.move();
ball.display();
}
4.2. Managing Multiple Objects with Arrays
To have many "balls," store them in an array and loop through the array to update and display each one.
let balls = [];
function setup() {
createCanvas(400, 400);
for (let i = 0; i < 10; i++) {
balls.push(new Ball(random(width), random(height), random(20, 50)));
}
}
function draw() {
background(220);
for (let i = 0; i < balls.length; i++) {
balls[i].move();
balls[i].display();
}
}
// See section 4.3 for the Ball class definition
4.3. Creating Custom Classes
Classes are blueprints for creating objects. They are ideal for defining reusable object types.
class Ball {
constructor(x, y, diameter) {
this.x = x;
this.y = y;
this.diameter = diameter;
this.speedX = random(-3, 3);
this.speedY = random(-3, 3);
this.color = color(random(255), random(255), random(255));
}
move() {
this.x += this.speedX;
this.y += this.speedY;
if (this.x > width - this.diameter/2 || this.x < this.diameter/2) {
this.speedX *= -1;
}
if (this.y > height - this.diameter/2 || this.y < this.diameter/2) {
this.speedY *= -1;
}
}
display() {
fill(this.color);
noStroke();
ellipse(this.x, this.y, this.diameter, this.diameter);
}
}
// This Ball class would be used with the array example above.