Students meet draw() (about 60 times a second) and variables that keep their value between frames, follow a circle's x frame by frame, see why background belongs in draw, fix a variable made inside draw, then move things down and at different speeds.
Load these into Waypoints Prepare: choose Load URL and paste the copied address, or download the file and import it. In Prepare, the worksheet's Teacher edition shows the answers; the student copy hides them.
Predict and Run 10 min · Investigate 15 min · Modify 10 min · Make 15 min
Read the unit primer first. The big idea is that draw() runs by itself, again and again; students never call it. A variable made at the top (outside functions) keeps its value between frames, and x = x + 2 reads as "make x two bigger", not as a maths equation. Students who did Python Foundations will recognise x = x + 1 from the variables lesson; the new part is that the loop is built in. The let in the bug task is the classic mistake: a variable made inside draw() starts again every frame. % (remainder) appears only in the Make step's text. The playground's number in the corner is text(x, 10, 20).
Seeing that draw() repeats, so a variable made inside it starts again. The trace table and the let-in-draw bug are for that.
| What you will see | A question to ask | The fix |
|---|---|---|
| The circle does not move. | Is the variable changed inside draw(), and made outside it? | let x = 0; goes at the top, outside every function; x = x + 2; goes inside draw(). |
| A red line saying x is not defined. | Where is let x = 0;? | Put it at the top of the sketch, above setup(). |
| A smear instead of a moving circle. | Is background(...) the first line in draw()? | Move it to the first line of draw(). |
| Both circles move together. | Do they use the same variable? | Make a second variable for the second circle. |
One possible solution for each task. Other correct programs are fine.
let y = 0;
function setup() {
createCanvas(300, 200);
}
function draw() {
background(20, 30, 60);
fill(255, 210, 0);
circle(150, y, 40);
fill(255);
text(y, 10, 20);
y = y + 2;
}
let x = 0;
let y = 0;
function setup() {
createCanvas(300, 200);
}
function draw() {
background(20, 30, 60);
fill(255, 210, 0);
circle(x, 60, 40);
fill(255, 120, 160);
circle(300 - y, 140, 30);
x = x + 2;
y = y + 4;
}
let t = 0;
function setup() {
createCanvas(300, 200);
}
function draw() {
background(20, 30, 60);
t = t + 1;
fill(255, 210, 0);
circle(t % 300, 60, 30);
fill(255, 120, 160);
circle(300 - (t % 300), 140, 30);
fill(255);
text(t, 10, 20);
}
Stretch: Make a circle that moves in both directions at once (x and y), or one that grows and shrinks.
Support: Give students the sketch with let y = 0; already made, and ask for the draw() changes only.
Why is let x = 0; at the top and not inside draw()?
Inside draw() it would be made again every frame and go back to 0; at the top it keeps its value.
Next lesson: if, so circles can bounce, and the mouse.