Working with Multiple Object Instances
Creating and managing arrays of game objects.
Working with Multiple Object Instances
// Define Enemy constructor
function Enemy(x, y, size, color, ctx) {
this.x = x;
this.y = y;
this.size = size;
this.color = color;
this.ctx = ctx;
this.update = function () { /* move enemy */ };
this.draw = function () { /* draw enemy */ };
}
// Create a mixed array of objects
const gameObjects = [
new Player(50, 50, 11, 'red', ctx),
new Enemy(200, 100, 10, 'purple', ctx),
new Enemy(300, 100, 10, 'green', ctx),
];
// Iterate and operate uniformly
gameObjects.forEach(obj => obj.update());
gameObjects.forEach(obj => obj.draw(ctx));
| Concept | Detail |
|---|---|
| Uniform interface | All objects share update() and draw() — the loop code stays simple regardless of object type. |
| Dynamic management | Push new objects or splice old ones from the array without rewriting the loop. |
| Scalability | Hundreds of enemies, projectiles and power-ups can be managed with the same loop. |
Activity — complete the code
Complete the code correctly to mark this lesson as complete automatically.
Complete the mixed array of game objects and the uniform loop.
const gameObjects = [Player(50, 50, 11, "red", ctx),Enemy(200, 100, 10, "purple", ctx),new Enemy(300, 100, 10, "green", ctx),];// Iterate and operate uniformlygameObjects.forEach(obj => obj.());gameObjects.forEach(obj => obj.(ctx));