← Drawing and animation with p5.js

Objects and stars

Keep everything about one star (its place and its speed) together in an object, and move a whole list of them.

A falling star has a place, a speed and a size. An object keeps them together, so a hundred stars are a hundred objects, not three hundred loose numbers.

An object holds named values together: { x: 20, y: 30, speed: 2 }. Each name is a property, read with a dot: star.y is that star's y. You change one the same way: star.y = star.y + star.speed;.

A list of objects is a list of things, each with its own values: stars. The loop to visit each one is the easiest kind:

for (let star of stars) {
  // star is each object in turn
}

Read it as "for each star in stars". It does not need a counter at all.

The hard part is the dot. Inside the loop, speed on its own means nothing: it is star.speed that is this star's speed. The error message "speed is not defined" is the clue.

PredictRead the code and say what it will do before you run anything. A wrong guess is fine: it shows you what to look for.

Predict

sketch.js
function setup() {
  let star = { x: 20, y: 30, speed: 2 };
  star.y = star.y + star.speed;
  console.log(star.y);
}

Work out star.y line by line.

What does console.log(star.y) show?

RunRun it and compare the result with your prediction.

Run

Each star is an object with its own x, y and speed. draw() visits every star in the list, draws it, moves it, and sends it back to the top if it has fallen off the bottom. Press Run again and watch how the speeds differ.

sketch.js
let stars = [];

function setup() {
  createCanvas(300, 200);
  for (let i = 0; i < 6; i++) {
    stars.push({ x: 25 + i * 50, y: random(200), speed: random(1, 3) });
  }
}

function draw() {
  background(20, 30, 60);
  fill(255, 210, 0);
  for (let star of stars) {
    circle(star.x, star.y, 12);
    star.y = star.y + star.speed;
    if (star.y > 210) {
      star.y = -10;
    }
  }
}
Try it yourselfYour edits are saved in this browser.

InvestigateTrace how each line of code connects to what you see.

Investigate

sketch.js
let stars = [];

function setup() {
  createCanvas(300, 200);
  for (let i = 0; i < 6; i++) {
    stars.push({ x: 25 + i * 50, y: random(200), speed: random(1, 3) });
  }
}

function draw() {
  background(20, 30, 60);
  fill(255, 210, 0);
  for (let star of stars) {
    circle(star.x, star.y, 12);
    star.y = star.y + star.speed;
    if (star.y > 210) {
      star.y = -10;
    }
  }
}

Match code with meaning.

Where each speed lives.

A name that p5 does not know.

Match each line with what it does.

stars.push({ x: 25, y: 10, speed: 2 });
for (let star of stars) {
star.y = star.y + star.speed;
circle(star.x, star.y, 12);

Why does each star fall at its own speed?

This stops with an error: speed is not defined. Click the line that causes it.

ModifyChange the code on purpose and check the result.

Modify

Make 12 stars, spread across the canvas.

Need a hint?

Two numbers in setup() decide how many stars there are and where they start.

Another hint

Change 6 to 12 in the loop, and change the 50 so they spread across the 300 pixels.

Give each star its own size.

Need a hint?

A property is added where the star is made, and read where it is drawn.

Another hint

Add size: random(6, 18) to the object in push, and use star.size in circle.

Try it yourselfYour edits are saved in this browser.

Give each star its own size.

    Run your program. This ticks when your code does all of the above.

    MakeBuild something new using what you have learned. Expect a few tries; that is normal.

    Another list

    Add a second kind of thing with its own list and its own loop: clouds that drift sideways, snowflakes that wobble, bubbles that rise. Make each object with the properties it needs, push them in setup(), and move and draw them with a for (let ... of ...) loop in draw(). Draw the clouds before the stars so the stars are on top.

    Try it yourselfYour edits are saved in this browser.

    Info

    Where this leads

    You can now hold many things, each with its own values. Next: functions, so a piece of code has a name and you can use it again.

    You want to write the code that restarts a star at the top in one place and use it for stars, clouds and bubbles. What do you need?

    For teachers

    Students keep one star's place and speed in an object, read and change properties with a dot, make a list of objects with push and random, move them with a for-of loop, find a speed missing its star., and add a property and a second list of their own. About 55 minutes.

    Open the teacher guide: answers, solutions, slides and a worksheet.

    Students will be able to

    Before class

    Read the unit primer first. This is the Python Objects with turtles unit in JavaScript, without classes: one object per thing, a list of objects, a loop. { x: 20, y: 30 } is an object; star.y reads and changes a property. for (let star of stars) is the easy loop: no counter, and star is the object itself, so star.y = ... changes the real star. The classic slip is writing speed instead of star.speed; the playground's hint for "x is not defined" suggests spelling, so say the dot aloud when you meet it. The Predict uses console.log so students compare a printed number: the Output box sits under the sketch. This lesson uses random and push from the last one without re-teaching them.

    Running the lesson

    1. Predict: write the object on the board and cross out the old y when it changes.
    2. Run: ask where in the code each star's speed lives.
    3. Investigate: for the bug, ask 'whose speed is it?' and point at the star.
    4. Modify: students ask each other what a size property changes, then test.
    5. Make: choose a second kind of thing and list its properties before writing code.

    The hard part (on purpose)

    The dot: star.speed, not speed. Say it as 'this star's speed'.

    When students get stuck

    Stretch and support

    Stretch: Make the stars twinkle by changing their size a little every frame, or give each one a colour property chosen with random.

    Support: Give students the cloud objects and loop already written, and ask only for the stars' size property.

    Where it leads

    Next lesson: functions with parameters, so restarting a star, or drawing a flower, is code with a name.

    What each step is for

    Now you can
    Next lesson6. Functions of your ownGive a piece of code a name, hand it values with parameters, and get an answer back with return.