Chapter 1 deck Chapter 2 deck Chapter 3 deck Chapter 4 deck Chapter 5 deck Chapter 6 deck Chapter 7 deck Chapter 8 deck Chapter 9 deck Chapter 10 deck Chapter 11 deck Chapter 12 deck Chapter 13 deck Chapter 14 deck

Working with Multiple Object Instances

3 slides · use ←/→ or Space to navigate, F for fullscreen.

Reading view

← Back to the full Chapter 7 deck

Working with Multiple Object Instances
Fullscreen for presentation · Print / PDF for a handout
1 / 3
Lesson

Working with Multiple Object Instances

Creating and managing arrays of game objects.

Working with Multiple Object Instances

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));
ConceptDetail
Uniform interfaceAll objects share update() and draw() — the loop code stays simple regardless of object type.
Dynamic managementPush new objects or splice old ones from the array without rewriting the loop.
ScalabilityHundreds of enemies, projectiles and power-ups can be managed with the same loop.
Working with Multiple Object Instances

Activity — complete the code

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 uniformly
gameObjects.forEach(obj => obj.());
gameObjects.forEach(obj => obj.(ctx));