Game making in JavaScript
Meteor Dodge
Steer a spaceship with the arrow keys and dodge a storm of meteors that gets faster the longer you last.
Meteors rain down on your ship. Slide left and right to dodge them: three hits and you are done. The longer you survive, the higher your score, and the harder the storm gets. Today's new idea is the keyboard: the game remembers which keys are held down, so the ship glides smoothly while you hold an arrow.
You will learn
- Read the keyboard with key events
- Move a player and keep it on the screen
- Spot a collision between two things
- Make a game harder as it goes on
You will need
- A computer with a web browser and a keyboard
- The Web Studio, or Notepad
- Day 1, for the canvas and the game loop
Words to know
- event
- Something that happens, such as a key going down, that code can respond to.
- collision
- Two things on the screen touching, which the game has to notice.
- difficulty curve
- How a game gets harder as you play.
- frame
- One picture of the game. The game loop draws about sixty frames every second.
Step by step
Step 1: A sky full of stars
Choose Day 2: Meteor Dodge in the Web Studio. The page has a black canvas. The script fills an array with 60 stars, each with a random place and size, and
drawStarsdraws each one as a tiny square withfillRect.1<!DOCTYPE html>2<html>3 <head>4 <meta charset="utf-8">5 <title>Meteor Dodge</title>6 <link rel="stylesheet" href="style.css">7 </head>8 <body>9 <h1>Meteor Dodge</h1>10 <canvas id="game" width="480" height="360"></canvas>11 <p>Click the game, then use the arrow keys.</p>12 <script src="script.js"></script>13 </body>14</html>1body {2 font-family: Arial, sans-serif;3 text-align: center;4 background: #10002b;5 color: white;6}7 8canvas {9 background: black;10 border: 3px solid #7b2cbf;11 border-radius: 10px;12 max-width: 100%;13}1const canvas = document.getElementById("game");2const ctx = canvas.getContext("2d");3 4// 60 stars, each at a random place5const stars = [];6for (let i = 0; i < 60; i++) {7 stars.push({8 x: Math.random() * canvas.width,9 y: Math.random() * canvas.height,10 size: Math.random() * 2 + 111 });12}13 14function drawStars() {15 ctx.fillStyle = "white";16 for (const s of stars) {17 ctx.fillRect(s.x, s.y, s.size, s.size);18 }19}20 21drawStars();A starry sky. Step 2: Your ship
The ship is a triangle, drawn as a path:
moveTothe nose,lineToeach back corner, thenclosePathandfill. Its position is in theshipobject, so moving it later is just changingship.x.New: lines 13, 22 to 31 and 33.
1const canvas = document.getElementById("game");2const ctx = canvas.getContext("2d");3 4// 60 stars, each at a random place5const stars = [];6for (let i = 0; i < 60; i++) {7 stars.push({8 x: Math.random() * canvas.width,9 y: Math.random() * canvas.height,10 size: Math.random() * 2 + 111 });12}13const ship = { x: 240, y: 320, speed: 5 };14 15function drawStars() {16 ctx.fillStyle = "white";17 for (const s of stars) {18 ctx.fillRect(s.x, s.y, s.size, s.size);19 }20}21 22function drawShip() {23 ctx.fillStyle = "deepskyblue";24 ctx.beginPath();25 ctx.moveTo(ship.x, ship.y - 20);26 ctx.lineTo(ship.x - 16, ship.y + 14);27 ctx.lineTo(ship.x + 16, ship.y + 14);28 ctx.closePath();29 ctx.fill();30}31 32drawStars();33drawShip();A blue ship at the bottom of the sky. Step 3: Steer with the arrow keys
keysremembers which keys are down.keydownsets a key totrueandkeyupsets it back tofalse. Then the game loop moves the ship while an arrow is held, unless it is already at the edge.preventDefaultstops the arrow keys scrolling the page. Click the game, then try it.New: lines 14 and 33 to 57.
1const canvas = document.getElementById("game");2const ctx = canvas.getContext("2d");3 4// 60 stars, each at a random place5const stars = [];6for (let i = 0; i < 60; i++) {7 stars.push({8 x: Math.random() * canvas.width,9 y: Math.random() * canvas.height,10 size: Math.random() * 2 + 111 });12}13const ship = { x: 240, y: 320, speed: 5 };14const keys = {};15 16function drawStars() {17 ctx.fillStyle = "white";18 for (const s of stars) {19 ctx.fillRect(s.x, s.y, s.size, s.size);20 }21}22 23function drawShip() {24 ctx.fillStyle = "deepskyblue";25 ctx.beginPath();26 ctx.moveTo(ship.x, ship.y - 20);27 ctx.lineTo(ship.x - 16, ship.y + 14);28 ctx.lineTo(ship.x + 16, ship.y + 14);29 ctx.closePath();30 ctx.fill();31}32 33document.addEventListener("keydown", function (event) {34 keys[event.key] = true;35 if (event.key === "ArrowLeft" || event.key === "ArrowRight") {36 event.preventDefault();37 }38});39 40document.addEventListener("keyup", function (event) {41 keys[event.key] = false;42});43 44function loop() {45 ctx.clearRect(0, 0, canvas.width, canvas.height);46 drawStars();47 if (keys.ArrowLeft && ship.x > 20) {48 ship.x = ship.x - ship.speed;49 }50 if (keys.ArrowRight && ship.x < canvas.width - 20) {51 ship.x = ship.x + ship.speed;52 }53 drawShip();54 requestAnimationFrame(loop);55}56 57loop();Click the game, then hold the arrow keys to steer. Watch out Key names are written exactly:"ArrowLeft", with a capital A and a capital L.Step 4: Here come the meteors
Every 30 frames, half a second, a meteor starts just above the top with a random place, size and speed. Each frame they all fall, and the ones that have fallen off the bottom are filtered out, just like Day 1's balloons.
New: lines 15, 16, 32 to 42 and 66 to 87.
1const canvas = document.getElementById("game");2const ctx = canvas.getContext("2d");3 4// 60 stars, each at a random place5const stars = [];6for (let i = 0; i < 60; i++) {7 stars.push({8 x: Math.random() * canvas.width,9 y: Math.random() * canvas.height,10 size: Math.random() * 2 + 111 });12}13const ship = { x: 240, y: 320, speed: 5 };14const keys = {};15let meteors = [];16let frames = 0;17 18function drawStars() {19 ctx.fillStyle = "white";20 for (const s of stars) {21 ctx.fillRect(s.x, s.y, s.size, s.size);22 }23}24 25function drawShip() {26 ctx.fillStyle = "deepskyblue";27 ctx.beginPath();28 ctx.moveTo(ship.x, ship.y - 20);29 ctx.lineTo(ship.x - 16, ship.y + 14);30 ctx.lineTo(ship.x + 16, ship.y + 14);31 ctx.closePath();32 ctx.fill();33}34 35function drawMeteor(m) {36 ctx.fillStyle = "sienna";37 ctx.beginPath();38 ctx.arc(m.x, m.y, m.r, 0, Math.PI * 2);39 ctx.fill();40 ctx.fillStyle = "saddlebrown";41 ctx.beginPath();42 ctx.arc(m.x - m.r / 3, m.y - m.r / 4, m.r / 4, 0, Math.PI * 2);43 ctx.fill();44}45 46document.addEventListener("keydown", function (event) {47 keys[event.key] = true;48 if (event.key === "ArrowLeft" || event.key === "ArrowRight") {49 event.preventDefault();50 }51});52 53document.addEventListener("keyup", function (event) {54 keys[event.key] = false;55});56 57function loop() {58 ctx.clearRect(0, 0, canvas.width, canvas.height);59 drawStars();60 if (keys.ArrowLeft && ship.x > 20) {61 ship.x = ship.x - ship.speed;62 }63 if (keys.ArrowRight && ship.x < canvas.width - 20) {64 ship.x = ship.x + ship.speed;65 }66 frames = frames + 1;67 if (frames % 30 === 0) {68 meteors.push({69 x: Math.random() * canvas.width,70 y: -20,71 r: Math.random() * 12 + 10,72 speed: Math.random() * 2 + 2,73 gone: false74 });75 }76 for (const m of meteors) {77 m.y = m.y + m.speed;78 if (m.y > canvas.height + 30) {79 m.gone = true;80 }81 }82 meteors = meteors.filter(function (m) {83 return !m.gone;84 });85 for (const m of meteors) {86 drawMeteor(m);87 }88 drawShip();89 requestAnimationFrame(loop);90}91 92loop();Meteors fall. They pass straight through the ship, for now. Step 5: Crash!
A meteor hits the ship if the distance between their middles is less than the meteor's radius plus 14, about the size of the ship. Then it is removed and you lose a life. The score goes up by 1 every 10 frames you survive, and
write, like the one in Balloon Pop but in white, shows the score and lives at the top.New: lines 17, 18, 46 to 52, 90 to 96 and 105 to 108.
1const canvas = document.getElementById("game");2const ctx = canvas.getContext("2d");3 4// 60 stars, each at a random place5const stars = [];6for (let i = 0; i < 60; i++) {7 stars.push({8 x: Math.random() * canvas.width,9 y: Math.random() * canvas.height,10 size: Math.random() * 2 + 111 });12}13const ship = { x: 240, y: 320, speed: 5 };14const keys = {};15let meteors = [];16let frames = 0;17let score = 0;18let lives = 3;19 20function drawStars() {21 ctx.fillStyle = "white";22 for (const s of stars) {23 ctx.fillRect(s.x, s.y, s.size, s.size);24 }25}26 27function drawShip() {28 ctx.fillStyle = "deepskyblue";29 ctx.beginPath();30 ctx.moveTo(ship.x, ship.y - 20);31 ctx.lineTo(ship.x - 16, ship.y + 14);32 ctx.lineTo(ship.x + 16, ship.y + 14);33 ctx.closePath();34 ctx.fill();35}36 37function drawMeteor(m) {38 ctx.fillStyle = "sienna";39 ctx.beginPath();40 ctx.arc(m.x, m.y, m.r, 0, Math.PI * 2);41 ctx.fill();42 ctx.fillStyle = "saddlebrown";43 ctx.beginPath();44 ctx.arc(m.x - m.r / 3, m.y - m.r / 4, m.r / 4, 0, Math.PI * 2);45 ctx.fill();46}47 48function write(text, x, y, size) {49 ctx.fillStyle = "white";50 ctx.font = "bold " + size + "px Arial";51 ctx.textAlign = "center";52 ctx.fillText(text, x, y);53}54 55document.addEventListener("keydown", function (event) {56 keys[event.key] = true;57 if (event.key === "ArrowLeft" || event.key === "ArrowRight") {58 event.preventDefault();59 }60});61 62document.addEventListener("keyup", function (event) {63 keys[event.key] = false;64});65 66function loop() {67 ctx.clearRect(0, 0, canvas.width, canvas.height);68 drawStars();69 if (keys.ArrowLeft && ship.x > 20) {70 ship.x = ship.x - ship.speed;71 }72 if (keys.ArrowRight && ship.x < canvas.width - 20) {73 ship.x = ship.x + ship.speed;74 }75 frames = frames + 1;76 if (frames % 30 === 0) {77 meteors.push({78 x: Math.random() * canvas.width,79 y: -20,80 r: Math.random() * 12 + 10,81 speed: Math.random() * 2 + 2,82 gone: false83 });84 }85 for (const m of meteors) {86 m.y = m.y + m.speed;87 if (m.y > canvas.height + 30) {88 m.gone = true;89 }90 // has it hit the ship?91 const dx = m.x - ship.x;92 const dy = m.y - ship.y;93 if (Math.sqrt(dx * dx + dy * dy) < m.r + 14) {94 m.gone = true;95 lives = lives - 1;96 }97 }98 meteors = meteors.filter(function (m) {99 return !m.gone;100 });101 for (const m of meteors) {102 drawMeteor(m);103 }104 drawShip();105 if (frames % 10 === 0) {106 score = score + 1;107 }108 write("Score: " + score + " Lives: " + lives, canvas.width / 2, 28, 20);109 requestAnimationFrame(loop);110}111 112loop();Hits cost lives, and the score counts up as you survive. Step 6: Game over, and play again
When the lives run out, the loop writes Game over and stops.
startresets everything, so a click or Space starts a new game. The game now opens on a start screen and waits for you.New: lines 19, 58, 60 to 62, 69 to 84, 129 to 134 and 138 to 142.
1const canvas = document.getElementById("game");2const ctx = canvas.getContext("2d");3 4// 60 stars, each at a random place5const stars = [];6for (let i = 0; i < 60; i++) {7 stars.push({8 x: Math.random() * canvas.width,9 y: Math.random() * canvas.height,10 size: Math.random() * 2 + 111 });12}13const ship = { x: 240, y: 320, speed: 5 };14const keys = {};15let meteors = [];16let frames = 0;17let score = 0;18let lives = 3;19let playing = false;20 21function drawStars() {22 ctx.fillStyle = "white";23 for (const s of stars) {24 ctx.fillRect(s.x, s.y, s.size, s.size);25 }26}27 28function drawShip() {29 ctx.fillStyle = "deepskyblue";30 ctx.beginPath();31 ctx.moveTo(ship.x, ship.y - 20);32 ctx.lineTo(ship.x - 16, ship.y + 14);33 ctx.lineTo(ship.x + 16, ship.y + 14);34 ctx.closePath();35 ctx.fill();36}37 38function drawMeteor(m) {39 ctx.fillStyle = "sienna";40 ctx.beginPath();41 ctx.arc(m.x, m.y, m.r, 0, Math.PI * 2);42 ctx.fill();43 ctx.fillStyle = "saddlebrown";44 ctx.beginPath();45 ctx.arc(m.x - m.r / 3, m.y - m.r / 4, m.r / 4, 0, Math.PI * 2);46 ctx.fill();47}48 49function write(text, x, y, size) {50 ctx.fillStyle = "white";51 ctx.font = "bold " + size + "px Arial";52 ctx.textAlign = "center";53 ctx.fillText(text, x, y);54}55 56document.addEventListener("keydown", function (event) {57 keys[event.key] = true;58 if (event.key === "ArrowLeft" || event.key === "ArrowRight" || event.key === " ") {59 event.preventDefault();60 }61 if (event.key === " " && !playing) {62 start();63 }64});65 66document.addEventListener("keyup", function (event) {67 keys[event.key] = false;68});69 70canvas.addEventListener("click", function () {71 if (!playing) {72 start();73 }74});75 76function start() {77 meteors = [];78 frames = 0;79 score = 0;80 lives = 3;81 ship.x = 240;82 playing = true;83 loop();84}85 86function loop() {87 ctx.clearRect(0, 0, canvas.width, canvas.height);88 drawStars();89 if (keys.ArrowLeft && ship.x > 20) {90 ship.x = ship.x - ship.speed;91 }92 if (keys.ArrowRight && ship.x < canvas.width - 20) {93 ship.x = ship.x + ship.speed;94 }95 frames = frames + 1;96 if (frames % 30 === 0) {97 meteors.push({98 x: Math.random() * canvas.width,99 y: -20,100 r: Math.random() * 12 + 10,101 speed: Math.random() * 2 + 2,102 gone: false103 });104 }105 for (const m of meteors) {106 m.y = m.y + m.speed;107 if (m.y > canvas.height + 30) {108 m.gone = true;109 }110 // has it hit the ship?111 const dx = m.x - ship.x;112 const dy = m.y - ship.y;113 if (Math.sqrt(dx * dx + dy * dy) < m.r + 14) {114 m.gone = true;115 lives = lives - 1;116 }117 }118 meteors = meteors.filter(function (m) {119 return !m.gone;120 });121 for (const m of meteors) {122 drawMeteor(m);123 }124 drawShip();125 if (frames % 10 === 0) {126 score = score + 1;127 }128 write("Score: " + score + " Lives: " + lives, canvas.width / 2, 28, 20);129 if (lives <= 0) {130 playing = false;131 write("Game over!", canvas.width / 2, 170, 44);132 write("Click or press Space to play again", canvas.width / 2, 210, 18);133 return;134 }135 requestAnimationFrame(loop);136}137 138// the start screen139drawStars();140drawShip();141write("Meteor Dodge", canvas.width / 2, 160, 44);142write("Click or press Space to start", canvas.width / 2, 200, 18);Click or press Space to start, then dodge! Step 7: Harder and harder
Make the storm grow. The gap between meteors shrinks from 30 frames to as few as 8 as the score rises, and every meteor falls faster.
bestremembers your best score until the page is closed.New: lines 20, 97 to 99, 104, 131, 134 to 136, 138 and 139.
1const canvas = document.getElementById("game");2const ctx = canvas.getContext("2d");3 4// 60 stars, each at a random place5const stars = [];6for (let i = 0; i < 60; i++) {7 stars.push({8 x: Math.random() * canvas.width,9 y: Math.random() * canvas.height,10 size: Math.random() * 2 + 111 });12}13const ship = { x: 240, y: 320, speed: 5 };14const keys = {};15let meteors = [];16let frames = 0;17let score = 0;18let lives = 3;19let playing = false;20let best = 0;21 22function drawStars() {23 ctx.fillStyle = "white";24 for (const s of stars) {25 ctx.fillRect(s.x, s.y, s.size, s.size);26 }27}28 29function drawShip() {30 ctx.fillStyle = "deepskyblue";31 ctx.beginPath();32 ctx.moveTo(ship.x, ship.y - 20);33 ctx.lineTo(ship.x - 16, ship.y + 14);34 ctx.lineTo(ship.x + 16, ship.y + 14);35 ctx.closePath();36 ctx.fill();37}38 39function drawMeteor(m) {40 ctx.fillStyle = "sienna";41 ctx.beginPath();42 ctx.arc(m.x, m.y, m.r, 0, Math.PI * 2);43 ctx.fill();44 ctx.fillStyle = "saddlebrown";45 ctx.beginPath();46 ctx.arc(m.x - m.r / 3, m.y - m.r / 4, m.r / 4, 0, Math.PI * 2);47 ctx.fill();48}49 50function write(text, x, y, size) {51 ctx.fillStyle = "white";52 ctx.font = "bold " + size + "px Arial";53 ctx.textAlign = "center";54 ctx.fillText(text, x, y);55}56 57document.addEventListener("keydown", function (event) {58 keys[event.key] = true;59 if (event.key === "ArrowLeft" || event.key === "ArrowRight" || event.key === " ") {60 event.preventDefault();61 }62 if (event.key === " " && !playing) {63 start();64 }65});66 67document.addEventListener("keyup", function (event) {68 keys[event.key] = false;69});70 71canvas.addEventListener("click", function () {72 if (!playing) {73 start();74 }75});76 77function start() {78 meteors = [];79 frames = 0;80 score = 0;81 lives = 3;82 ship.x = 240;83 playing = true;84 loop();85}86 87function loop() {88 ctx.clearRect(0, 0, canvas.width, canvas.height);89 drawStars();90 if (keys.ArrowLeft && ship.x > 20) {91 ship.x = ship.x - ship.speed;92 }93 if (keys.ArrowRight && ship.x < canvas.width - 20) {94 ship.x = ship.x + ship.speed;95 }96 frames = frames + 1;97 // meteors come faster and more often as the score goes up98 const gap = Math.max(8, 30 - Math.floor(score / 10));99 if (frames % gap === 0) {100 meteors.push({101 x: Math.random() * canvas.width,102 y: -20,103 r: Math.random() * 12 + 10,104 speed: Math.random() * 2 + 2 + score / 50,105 gone: false106 });107 }108 for (const m of meteors) {109 m.y = m.y + m.speed;110 if (m.y > canvas.height + 30) {111 m.gone = true;112 }113 // has it hit the ship?114 const dx = m.x - ship.x;115 const dy = m.y - ship.y;116 if (Math.sqrt(dx * dx + dy * dy) < m.r + 14) {117 m.gone = true;118 lives = lives - 1;119 }120 }121 meteors = meteors.filter(function (m) {122 return !m.gone;123 });124 for (const m of meteors) {125 drawMeteor(m);126 }127 drawShip();128 if (frames % 10 === 0) {129 score = score + 1;130 }131 write("Score: " + score + " Best: " + best + " Lives: " + lives, canvas.width / 2, 28, 20);132 if (lives <= 0) {133 playing = false;134 if (score > best) {135 best = score;136 }137 write("Game over!", canvas.width / 2, 170, 44);138 write("Best score: " + best, canvas.width / 2, 210, 22);139 write("Click or press Space to play again", canvas.width / 2, 245, 18);140 return;141 }142 requestAnimationFrame(loop);143}144 145// the start screen146drawStars();147drawShip();148write("Meteor Dodge", canvas.width / 2, 160, 44);149write("Click or press Space to start", canvas.width / 2, 200, 18);The finished Meteor Dodge. How long can you last?
Test it
Tick each one when it works. If one does not, look back at the step it comes from.
Stretch challenges
Finished early? Try these. Each one has a hint if you get stuck.
Up and down
Let the ship move up and down too, but only in the bottom half of the sky.
Show a hint
Copy the
ArrowLeftcode for"ArrowUp"and"ArrowDown", changingship.y. Keepship.ybetween 180 and 340.Shield
Collect a power up that makes the ship safe from hits for five seconds.
Show a hint
Make a falling green circle like a meteor. Catching it sets
shield = 300(frames). Each frame, take 1 off, and only lose a life whenshieldis 0. Draw a ring round the ship while it is on.Explosions
Draw a quick orange flash where a meteor hits.
Show a hint
Push
{ x, y, life: 20 }into an array of flashes on a hit. Each frame, draw each flash as a circle that grows as its life runs out, and filter out the ones that are finished.
The finished code
Show the whole game
1<!DOCTYPE html>2<html>3 <head>4 <meta charset="utf-8">5 <title>Meteor Dodge</title>6 <link rel="stylesheet" href="style.css">7 </head>8 <body>9 <h1>Meteor Dodge</h1>10 <canvas id="game" width="480" height="360"></canvas>11 <p>Click the game, then use the arrow keys.</p>12 <script src="script.js"></script>13 </body>14</html>1body {2 font-family: Arial, sans-serif;3 text-align: center;4 background: #10002b;5 color: white;6}7 8canvas {9 background: black;10 border: 3px solid #7b2cbf;11 border-radius: 10px;12 max-width: 100%;13}1const canvas = document.getElementById("game");2const ctx = canvas.getContext("2d");3 4// 60 stars, each at a random place5const stars = [];6for (let i = 0; i < 60; i++) {7 stars.push({8 x: Math.random() * canvas.width,9 y: Math.random() * canvas.height,10 size: Math.random() * 2 + 111 });12}13const ship = { x: 240, y: 320, speed: 5 };14const keys = {};15let meteors = [];16let frames = 0;17let score = 0;18let lives = 3;19let playing = false;20let best = 0;21 22function drawStars() {23 ctx.fillStyle = "white";24 for (const s of stars) {25 ctx.fillRect(s.x, s.y, s.size, s.size);26 }27}28 29function drawShip() {30 ctx.fillStyle = "deepskyblue";31 ctx.beginPath();32 ctx.moveTo(ship.x, ship.y - 20);33 ctx.lineTo(ship.x - 16, ship.y + 14);34 ctx.lineTo(ship.x + 16, ship.y + 14);35 ctx.closePath();36 ctx.fill();37}38 39function drawMeteor(m) {40 ctx.fillStyle = "sienna";41 ctx.beginPath();42 ctx.arc(m.x, m.y, m.r, 0, Math.PI * 2);43 ctx.fill();44 ctx.fillStyle = "saddlebrown";45 ctx.beginPath();46 ctx.arc(m.x - m.r / 3, m.y - m.r / 4, m.r / 4, 0, Math.PI * 2);47 ctx.fill();48}49 50function write(text, x, y, size) {51 ctx.fillStyle = "white";52 ctx.font = "bold " + size + "px Arial";53 ctx.textAlign = "center";54 ctx.fillText(text, x, y);55}56 57document.addEventListener("keydown", function (event) {58 keys[event.key] = true;59 if (event.key === "ArrowLeft" || event.key === "ArrowRight" || event.key === " ") {60 event.preventDefault();61 }62 if (event.key === " " && !playing) {63 start();64 }65});66 67document.addEventListener("keyup", function (event) {68 keys[event.key] = false;69});70 71canvas.addEventListener("click", function () {72 if (!playing) {73 start();74 }75});76 77function start() {78 meteors = [];79 frames = 0;80 score = 0;81 lives = 3;82 ship.x = 240;83 playing = true;84 loop();85}86 87function loop() {88 ctx.clearRect(0, 0, canvas.width, canvas.height);89 drawStars();90 if (keys.ArrowLeft && ship.x > 20) {91 ship.x = ship.x - ship.speed;92 }93 if (keys.ArrowRight && ship.x < canvas.width - 20) {94 ship.x = ship.x + ship.speed;95 }96 frames = frames + 1;97 // meteors come faster and more often as the score goes up98 const gap = Math.max(8, 30 - Math.floor(score / 10));99 if (frames % gap === 0) {100 meteors.push({101 x: Math.random() * canvas.width,102 y: -20,103 r: Math.random() * 12 + 10,104 speed: Math.random() * 2 + 2 + score / 50,105 gone: false106 });107 }108 for (const m of meteors) {109 m.y = m.y + m.speed;110 if (m.y > canvas.height + 30) {111 m.gone = true;112 }113 // has it hit the ship?114 const dx = m.x - ship.x;115 const dy = m.y - ship.y;116 if (Math.sqrt(dx * dx + dy * dy) < m.r + 14) {117 m.gone = true;118 lives = lives - 1;119 }120 }121 meteors = meteors.filter(function (m) {122 return !m.gone;123 });124 for (const m of meteors) {125 drawMeteor(m);126 }127 drawShip();128 if (frames % 10 === 0) {129 score = score + 1;130 }131 write("Score: " + score + " Best: " + best + " Lives: " + lives, canvas.width / 2, 28, 20);132 if (lives <= 0) {133 playing = false;134 if (score > best) {135 best = score;136 }137 write("Game over!", canvas.width / 2, 170, 44);138 write("Best score: " + best, canvas.width / 2, 210, 22);139 write("Click or press Space to play again", canvas.width / 2, 245, 18);140 return;141 }142 requestAnimationFrame(loop);143}144 145// the start screen146drawStars();147drawShip();148write("Meteor Dodge", canvas.width / 2, 160, 44);149write("Click or press Space to start", canvas.width / 2, 200, 18);Notes for the teacher
Timing
- 10 minutes: steps 1 and 2.
- 15 minutes: step 3. Talk through why the game remembers held keys instead of moving once per key press: try it the other way and the ship stutters.
- 25 minutes: steps 4 to 7.
Mistakes to look out for
- The arrow keys do nothing: the game must be clicked first, so it hears the keyboard.
"arrowleft"or"Left"instead of"ArrowLeft".- Lives that vanish all at once: the meteor is not marked
goneafter it hits, so it hits again on every frame it overlaps. frames % gapwith a gap that is not a whole number never equals 0.Math.floorkeeps it whole.
Going further
Collision detection is a central idea in games programming. Circles are the easiest case: compare the distance between centres with the sum of the radii.