Find a course

Module 3: Arrays and ObjectsLesson 6 of 1112 min

Objects for Players and Enemies

Describe a player or enemy as one object with named properties such as x, y, speed and color, and manage whole armies with arrays of objects.

Step 1 of 11Learn

Grouping related values

A player in a 2D game has a position (x and y), a size, a speed, a color, maybe health and a name. You could make separate variables, playerX, playerY, playerSpeed, but add three enemies and you're juggling dozens of loose variables. An object groups related values under one name:

let player = {
  x: 100,
  y: 250,
  width: 32,
  height: 32,
  speed: 4,
  color: "teal",
  health: 100
};

Each line inside the curly braces is a property: a name, a colon and a value, separated from the next by a comma. You read and change properties with dot notation:

player.x += player.speed;   // move right
player.health -= 10;        // take damage
console.log(player.color);  // "teal"

You can even add new properties later: player.hasJetpack = true;.

The difference from arrays: arrays are ordered lists you access by number (enemies[0]), while objects are labeled bundles you access by name (player.x). Use an array when you have many of the same kind of thing and an object when you're describing one thing with several features.

Step 2 of 11Diagram

One object, many properties

Tap a property to see how to use it with dot notation.

One object, many propertiesParts diagram: player, x: 100, y: 250, width: 32, height: 32, speed: 4, color: "teal", health: 100.playerx: 100y: 250width: 32,height: 32speed: 4color: "teal"health: 100

Tap a shape with to see more.

player
x: 100

player.x += player.speed; moves right.

y: 250

Bigger y is lower on the canvas.

width: 32, height: 32

Used for drawing and collisions.

speed: 4

Pixels per frame.

color: "teal"

console.log(player.color) prints "teal".

health: 100

player.health -= 10; takes damage.

Step 3 of 11Practice · Sort into groups

Would you store each of these as an array or an object?

Tap an item, then tap its group (or drag it there).

Step 4 of 11Compare

Array or object?

AspectArray [ ]Object { }
HoldsA list of similar thingsNamed facts about one thing
Access byIndex number: enemies[2]Property name: player.health
Order matters?YesNo, names matter
Game exampleHigh scores, enemies, inventoryThe player, one enemy, settings

Step 5 of 11Learn

Arrays of objects

Here's where it all comes together. Almost every game stores its enemies, bullets, coins and particles as arrays of objects:

let enemies = [
  { x: 50,  y: 0, speed: 2, alive: true },
  { x: 200, y: 0, speed: 3, alive: true },
  { x: 350, y: 0, speed: 1, alive: true }
];

Each element is an object, so you combine an index and a dot to reach a property: enemies[1].speed is 3. In a loop, you update every enemy with the same code:

for (const e of enemies) {
  e.y += e.speed;
}

Each enemy falls at its own speed, but you wrote the movement rule once. Spawning a new enemy is a single push:

enemies.push({ x: 120, y: 0, speed: 2, alive: true });

And clearing out destroyed enemies uses filter, which builds a new array keeping only the elements that pass a test:

enemies = enemies.filter(e => e.alive);

This is exactly how real games handle hundreds of moving things: one array, one loop, one set of rules, and each object carrying its own data. When you design a new game object, start by asking which properties it needs, then write one function that updates any object of that kind.

Step 6 of 11Practice · Choose one

Using the enemies array above, which expression gives the x position of the third enemy?

Step 7 of 11Learn

Functions that work on objects

Functions and objects make a powerful team. Instead of writing movePlayer and moveEnemy separately, write one function that moves any object with x, y and velocity properties:

function move(obj) {
  obj.x += obj.vx;
  obj.y += obj.vy;
}

move(player);
for (const e of enemies) move(e);

Here vx and vy are the horizontal and vertical velocity: how many pixels the object moves per frame on each axis. A positive vx moves right, a negative one moves left.

There's one important behavior to understand. When you pass an object to a function, the function receives a reference to the same object, not a copy. Changing obj.x inside move changes the real player. That's what makes move(player) work. But it also means this surprise:

let a = { score: 10 };
let b = a;
b.score = 99;
console.log(a.score);  // 99

a and b are two names for one object. If you truly need a separate copy, for example to remember the starting position for a level restart, create one with { ...a }, which copies the properties into a new object.

Objects are passed by reference: the variables p1 and p2 both point to the same object, so changing p2.x also changes p1.xp1p2{ x: 50 }one objectlet p2 = p1; p2.x = 50; → p1.x is 50 too

Step 8 of 11Note

Step 9 of 11Practice · Code challenge

Write makeEnemy(x, speed) that returns a new object with properties x (from the argument), y set to 0, speed (from the argument) and alive set to true. Then write fall(enemy) that increases the enemy's y by its speed and returns the enemy.

Runs in a sandbox in your browser.
  • makeEnemy(40, 3)
  • fall(makeEnemy(10, 5)).y
  • fall(fall(makeEnemy(0, 2))).y

Step 10 of 11Note

Step 11 of 11Practice · True or false

After let p1 = { x: 0 }; let p2 = p1; p2.x = 50;, the value of p1.x is still 0.