Inside draw(), add these two lines:
Inside draw()
clear();
elevator.vel.y = cos(frameCount * 2.2) * 6;
- clear() erases the canvas each frame so sprites don't leave trails.
- cos(frameCount * 2.2) * 6 uses a cosine wave to smoothly move the elevator up and down.
- frameCount is a built-in counter that increases by 1 every frame.
Your complete solution should look like this:
Complete Solution
let square;
let elevator;
function setup() {
new Canvas(450, 450);
world.gravity.y = 10;
square = new Sprite();
square.width = 30;
square.height = 30;
square.bounciness = 0.1;
square.y = 40;
elevator = new Sprite();
elevator.width = 100;
elevator.height = 15;
elevator.color = '#99d46a';
elevator.collider = 'kinematic';
}
function draw() {
clear();
elevator.vel.y = cos(frameCount * 2.2) * 6;
}
🚀
Hit Run and watch the square fall onto the moving elevator! On the next problem, you'll write setup() and draw() from scratch — no steps provided. Close your notes and try to recall the structure!