0 Spicy Yoghurt | Last updated: 6 November 2026 | HTML5 game tutorial
Add sound effects and music
Learn how to add sound effects and music to your JavaScript game with the Web Audio API. Play several sounds at once, control their volume and panning, make a sound a little different every time it plays and create your own sound effects in code. By the end of this tutorial, the bee game from this series will have sound effects and its own music.
Part of the HTML5 game tutorial series
This tutorial builds on the bee game from the part about game states, and gives it sound effects and music. Just jumping in? Use the complete code at the end of the game states part as your starting point.
Show all partsHide all parts
There's more to sound in a game than just playing a file. First, you'll see why HTML's audio element isn't enough for a game, and how the Web Audio API loads and plays sounds. Then you'll turn the sound on when the player first clicks, add a mute button and background music, and make sure no two hits or bumps sound exactly the same. Finally, you'll make sound effects of your own, without any audio files.
Play a sound with the audio element
The quickest way to play a sound in JavaScript is the audio element. You may know it as the <audio> tag in HTML, but you can also create one in JavaScript without adding it to your page:
let buzzSound = new Audio('bee-buzz.mp3');
buzzSound.play();new Audio() creates an audio element and starts loading the file, and play() plays it. That's all you need for a button that plays a sound now and then.
In a game, it falls short. Click the canvas below a few times in a row, as fast as you can:
Every blue bar on the timeline is a sound, and every mark below it is a click. Most of your clicks don't do anything, so they're marked with a red X. An audio element plays one sound at a time. Call play() while it's still playing, and nothing happens.
You could make a new audio element every time you play a sound, but that comes with its own problems. Every element has to load and start on its own, and on some devices, especially phones, there's a short delay before you hear the sound. In a game, a sound has to play at the exact moment something happens on screen. So what do you use instead?
Use the Web Audio API instead
The Web Audio API is made for this. It decodes a sound file once and keeps it in memory. From there, you can play it as often as you like, even ten times at once, and it starts right away. You also decide how each sound plays: how loud, how high or low it sounds, and whether it comes from the left or the right.
In the Web Audio API, a sound travels through a chain of audio nodes. Each node does one thing and passes the sound on to the next one. The shortest chain has two nodes: a source that plays the sound, and the destination, which is your speakers:
Everything starts with an AudioContext. It holds all the nodes and keeps track of the time. One is enough for your whole game, so create it once, in a new function called createAudio(), which you'll call from init() when the page loads:
// One AudioContext for all the sound in the game
let audioContext;
function createAudio() {
audioContext = new AudioContext();
}As you go through this tutorial, the chain gets a few more nodes: one for the volume and one for panning left and right.
Load sound files with fetch()
Before you can play a sound, you need to load it. fetch() downloads the file, and arrayBuffer() gives you its raw bytes. decodeAudioData() then turns those bytes into an AudioBuffer, the sound itself, ready in memory:
function loadSound(url) {
// Download the file and decode it into an AudioBuffer
return fetch(url)
.then(function (response) {
return response.arrayBuffer();
})
.then(function (data) {
return audioContext.decodeAudioData(data);
})
.catch(function () {
// No sound, but the game still works
return null;
});
}Just like loadImage() from the tutorial about images and sprite animations, loadSound() returns a Promise, which gives you the AudioBuffer as soon as the file has loaded. If a file doesn't load, catch() gives back null, so a missing sound never stops your game.
Your game has a few sounds, so keep them all in one list, with a volume for each sound. You'll use the vary value further down this page:
// The sound files, with a volume for each sound and how much
// its pitch can vary every time it plays (0.1 is 10%)
const soundUrl =
'https://spicyyoghurt.com/img/tutorials/' +
'develop_a_html5_game/';
const soundFiles = {
start: {file: 'bee-start.mp3', volume: 0.5, vary: 0},
hit: {file: 'bee-hit.mp3', volume: 0.7, vary: 0.1},
buzz: {file: 'bee-buzz.mp3', volume: 0.4, vary: 0.1},
bump: {file: 'bee-bump.mp3', volume: 0.3, vary: 0.15},
gameOver: {file: 'bee-game-over.mp3', volume: 0.6, vary: 0},
best: {file: 'bee-best.mp3', volume: 0.6, vary: 0},
music: {file: 'bee-music.mp3', volume: 0.35, vary: 0}
};
// The decoded sounds by name
let sounds = {};
function loadSounds() {
let names = Object.keys(soundFiles);
let loading = names.map(function (name) {
return loadSound(soundUrl + soundFiles[name].file);
});
// Keep each decoded sound under its name
return Promise.all(loading).then(function (buffers) {
for (let i = 0; i < names.length; i++) {
sounds[names[i]] = buffers[i];
}
});
}The names say what a sound is for, not what it sounds like. That way, you can swap bee-hit.mp3 for a better sound later, and the code that plays it stays the same.
The game should only start when the sprite sheet and the sounds are ready. In init(), call createAudio() first, so decodeAudioData() has an AudioContext to work with. Then replace the code that loads the sprite sheet with the code below, which uses Promise.all() to wait for both:
// Show the start screen when the sprite sheet
// and the sounds have loaded
let loading = [loadImage(spriteUrl), loadSounds()];
Promise.all(loading).then(function (results) {
Bee.sprite = results[0];
resetGame();
window.requestAnimationFrame(gameLoop);
});In the code above, soundUrl points to spicyyoghurt.com, so the sounds work right away. They're MP3 files, because every browser can play MP3 and the files are small. WAV files work in every browser too, but they're much bigger. The bee game's music is 0.4 MB as an MP3 and would be 4.5 MB as a WAV file.
To use your own sounds, put them in a folder next to your HTML file and set soundUrl to that folder, like 'audio/'. Then test your game on a local server, because if you open the HTML file straight from your computer, fetch() won't load them. Browsers block this for security reasons. You'll find more about it in the questions at the end of this page.
Play the same sound several times at once
To play a sound, create an AudioBufferSourceNode, give it the buffer and connect it to the destination:
function playSound(name) {
let source = audioContext.createBufferSource();
source.buffer = sounds[name];
source.connect(audioContext.destination);
source.start();
}A source node plays only once. After start(), you can't start it again, so you create a new one every time you play a sound. Don't worry about performance, because source nodes are very cheap to create. All the source nodes share the same buffer, so the sound itself is only in memory once.
Here's the click demo from earlier again, now with the Web Audio API. Click it as fast as you can:
This time, every click plays a sound, and the bars overlap.
Turn on the sound with the first click
Try this in your own game, and chances are you won't hear a thing. Open your browser's console, and you'll find a warning like this one: The AudioContext was not allowed to start. It must be resumed (or created) after a user gesture on the page.
Browsers don't let a page play any sound until the player interacts with it, for example with a click, a tap or a key press. That way, a website can't blast music at you the moment it opens. So an AudioContext that you create when the page loads starts out in the 'suspended' state. It doesn't play anything until you call resume() after a click or a key press.
The start screen of your game is the perfect spot for that. In the tutorial about JavaScript game states, you made a click, a tap or a key press on the start screen call startGame(). So turn on the sound in that function too:
function startGame() {
// The first click or key press also turns on the sound
audioContext.resume();
resetGame();
changeState(states.playing);
}On a touchscreen, there's one catch. The game starts as soon as your finger touches the screen, in onPointerDown(), but the browser only allows sound once you lift your finger again. So call resume() in onPointerUp() too:
function onPointerUp() {
pointer.isDown = false;
// On a touchscreen, the browser only allows sound
// once the finger lifts off the screen
audioContext.resume();
}On a phone, the start sound and the music still play. They just wait until you lift your finger, and then start.
When the sound is already on, resume() does nothing, so you can safely call it every time. The sounds load while the AudioContext is still suspended, so they're ready the moment the player starts. The warning stays in the console, but it's harmless. It only tells you that the sound has to wait for the first click.
Change the volume with a GainNode
Not every sound should be equally loud. Two bees bumping into each other should sound softer than the buzz of a new bee. Bumps happen all the time, but the buzz warns you that a new bee is on its way. A GainNode changes the volume of everything that goes through it. Its gain.value is the volume: 1 is the volume of the file, 0.5 is half the volume and 0 is silent.
Give every sound its own GainNode, and send all sounds through one more, the master volume. Now the chain looks like this:
Add a masterGain variable next to audioContext, and create the master volume in createAudio(), right after you create the AudioContext:
// Every sound goes through the master volume to the speakers
masterGain = audioContext.createGain();
masterGain.connect(audioContext.destination);In playSound(), replace source.connect(audioContext.destination) with these lines. They put a GainNode between the source and the master volume, and set its volume from soundFiles:
// The volume of this sound
let gain = audioContext.createGain();
gain.gain.value = soundFiles[name].volume;
source.connect(gain);
gain.connect(masterGain);In gain.gain.value, the first gain is the GainNode, and the second one is its volume.
Is a new sound file too loud for your game? Just change one number in the list.
Try a few values for masterGain.gain.value below. The bar on the right shows how loud the sound is right now:
Add a mute button
Every game needs a way to turn the sound off. People play games at work, on the train or late at night, when the rest of the house is asleep. With a master volume, that's easy. Set it to 0, and everything goes quiet:
let isMuted = false;
function toggleMute() {
isMuted = !isMuted;
localStorage.setItem('beeMuted', isMuted);
// Fade out quickly, so you don't hear a click
let volume = isMuted ? 0 : 1;
masterGain.gain.setTargetAtTime(
volume, audioContext.currentTime, 0.02
);
}You could set gain.value directly, but a sudden jump in volume can make a small click. setTargetAtTime() glides to the new volume instead, starting now, in a few hundredths of a second.
Players don't want to mute your game every time they visit, so toggleMute() saves the choice in local storage. Read it back in init(), once, when the page loads:
// Set up the sound, and check if you muted it last time
createAudio();
isMuted = localStorage.getItem('beeMuted') == 'true';
masterGain.gain.value = isMuted ? 0 : 1;Local storage turns every value into a string, and the string 'false' counts as true in an if statement. That's why the code compares the value to the string 'true'. The tutorial about local storage has more on this in its section on numbers and booleans.
The mute button is a speaker icon in the top-right corner, next to the pause button. It works just like the buttons from the game states tutorial. Check for a click on it in onPointerDown(), before the current state handles the click, so the button works on every game screen:
// The mute button in the top-right corner, on every screen
const muteButton = {x: 696, y: 14, width: 40, height: 40};
function onPointerDown(event) {
updatePointer(event);
// The mute button works on every screen
if (isOnButton(muteButton)) {
toggleMute();
return;
}
// The current state decides what the click or tap does
state.onPointerDown(event);
}The M key does the same. Check for it in onKeyDown() before the key goes to the current state. drawMuteButton() draws the speaker, with two waves when the sound is on and an X when it's off. You'll find both in the complete code at the end of this page.
Play background music
Music is a sound like any other, except that it has to keep playing. Set loop to true, and the source starts over every time it reaches the end:
// The music that's playing
let music = null;
function startMusic() {
music = audioContext.createBufferSource();
music.buffer = sounds.music;
music.loop = true;
music.connect(musicGain);
music.start();
}
function stopMusic() {
if (music) {
music.stop();
music = null;
}
}The music in this game is a free piano loop from Pixabay. The music has its own GainNode, musicGain, so you can turn down the music without touching the sound effects. You'll see how to create musicGain in the next section.
Start the music in startGame(), together with a short sound to tell the player that the game has begun:
function startGame() {
// The first click or key press also turns on the sound
audioContext.resume();
resetGame();
changeState(states.playing);
playSound('start');
startMusic();
}The music should stop when the player quits or the game is over. In the game states tutorial, a state can have an enter() function, which runs when the game switches to that state. The Quit button takes the game back to the start screen, so the start state's enter() is the place to stop the music:
start: {
enter() {
// Back on the start screen, the music stops
stopMusic();
},
// ... update(), draw() and the controls
},The game over state already saves the high score in its enter(), and sets isNewHighScore to true when you beat it. Stop the music there too, and play a short tune, a happy one for a new high score and a sad one otherwise:
gameover: {
enter() {
// ... save the high score
// Stop the music and play a short tune
stopMusic();
playSound(isNewHighScore ? 'best' : 'gameOver');
},
// ... update(), draw() and the controls
}Now click the canvas below to start the music, and click Restart a few times, just like you would in your game's pause menu. What's going wrong here?
Restart calls startGame(), which starts the music again. But Restart goes straight from the pause menu back to playing, so the game never goes through the start screen or the game over screen, and the old music never stops. Every restart adds another track. Each one starts at a different moment, so they're not even in sync.
The fix is one line, at the start of startMusic(). Stop the old track before you start a new one:
function startMusic() {
// Only one track at a time, so stop the old one first
stopMusic();
if (!sounds.music) {
return;
}
music = audioContext.createBufferSource();
music.buffer = sounds.music;
music.loop = true;
music.connect(musicGain);
music.start();
}Turn Stop previous track on in the demo and click Restart again. Now there's never more than one track playing.
Turn the music down when the game is paused
When the player opens the pause menu, you could just let the music keep playing. But many games make it softer and duller, as if it's coming from the room next door. That tells the player the game is waiting, without going completely silent.
A BiquadFilterNode with the type 'lowpass' does that. It lets the low notes through and filters out the high ones. Put it after musicGain, in createAudio(). musicGain and musicFilter are two more variables, declared next to masterGain:
// The music has its own volume, and a filter
// for when the game is paused
musicGain = audioContext.createGain();
musicGain.gain.value = soundFiles.music.volume;
musicFilter = audioContext.createBiquadFilter();
musicFilter.type = 'lowpass';
musicFilter.frequency.value = 20000;
musicGain.connect(musicFilter);
musicFilter.connect(masterGain);frequency is the cutoff frequency in hertz (Hz), roughly the highest note that gets through. 20,000 Hz is about as high as anyone can hear, so while you play, the filter has no effect. In the pause menu, it drops to 600 Hz, and the music plays at half its volume:
function muffleMusic(isMuffled) {
let now = audioContext.currentTime;
let volume = soundFiles.music.volume;
let frequency = 20000;
// Half as loud, and only the low notes
if (isMuffled) {
volume /= 2;
frequency = 600;
}
// Change smoothly instead of all at once
musicGain.gain.setTargetAtTime(volume, now, 0.1);
musicFilter.frequency.setTargetAtTime(frequency, now, 0.1);
}Call it when the game pauses and again when the pause ends. In the game states tutorial, you saw that enter() and exit() often come in pairs: what one turns on, the other turns off. That's exactly what the paused state needs:
paused: {
enter() {
// Soft, muffled music while the game is paused
muffleMusic(true);
},
exit() {
// And back to normal when the pause ends
muffleMusic(false);
},
// ... update(), draw() and the controls
},exit() also runs when the player picks Restart or Quit in the pause menu, so the music never stays muffled.
Try it below. Play the music and pause it, with Low-pass filter off and on. The bars at the bottom show the low notes on the left and the high notes on the right:
With the filter on, the bars on the right disappear as soon as you pause.
Pause audio when the player switches tabs
In the tutorial about the JavaScript game loop, you saw that the game loop stops when you switch to another tab. The sound doesn't. A sound that's already playing keeps going, and the music keeps looping.
Your game already has a visibilitychange listener that pauses the game in a hidden tab. Add a few lines to that listener to suspend the whole AudioContext as well, and to resume it when the player comes back:
document.addEventListener('visibilitychange', function () {
if (document.hidden) {
pauseGame();
// A hidden tab stops the game loop, but not the sound
audioContext.suspend();
} else if (state != states.start) {
audioContext.resume();
}
});suspend() freezes the AudioContext's clock, so the music picks up exactly where it left off. On the start screen, the sound stays off until the player clicks, just like when the page first loads. Try it in the finished game further down this page: start playing and switch to another tab.
Make a sound a little different every time it plays
A bump that sounds exactly the same every time gets boring fast, and in a busy game, you hear it a lot. Change the pitch a little every time, and it sounds much more natural.
A source node's playbackRate does that. At 1, the sound plays at its normal speed; at 1.1, a little faster and higher; and at 0.9, a little slower and lower. Set it in playSound(), right after you create the source:
// A slightly different pitch every time
let change = (Math.random() * 2 - 1) * soundFiles[name].vary;
source.playbackRate.value = 1 + change;Math.random() * 2 - 1 is a random number between -1 and 1. Multiply it by the vary value from soundFiles, and a bump with a vary of 0.15 plays at a rate between 0.85 and 1.15. The tunes for game over and a new high score have a vary of 0, because a melody at a random pitch sounds like a mistake. To learn more about generating random values, take a look at the tutorial about random numbers.
Click the canvas to play the same sound ten times, with Pitch variation off and on:
Prefer to think in notes? Use detune instead, which changes the pitch in cents. 100 cents is a half step, from one piano key to the very next one.
Pan a sound to the left or right
A bee that appears on the left should sound like it's on the left. A StereoPannerNode moves a sound between the left and right speakers. It goes between the sound's GainNode and the master volume:
Its pan goes from -1, all the way to the left, to 1, all the way to the right. Base it on the spot on the canvas where the sound happens:
// Left or right, based on where it happens on the canvas
let panner = audioContext.createStereoPanner();
panner.pan.value = (x - canvasWidth / 2) / canvasWidth;
source.connect(gain);
gain.connect(panner);
panner.connect(masterGain);At the left edge of the canvas, x is 0, and at the right edge it's canvasWidth, which is 750. The calculation turns that into a number from -0.5 to 0.5. That's only half the full range, and that's on purpose. A sound that plays in only one ear sounds odd on headphones.
playSound() takes x as a second argument, with the middle of the canvas as its default value: playSound(name, x = canvasWidth / 2). The buzz of a new bee comes from the spot where it will appear. In updateSpawning(), a red ring warns you one second before a new bee shows up. Add one line there to play the buzz:
if (spawnTimer < 1 && !nextBee) {
nextBee = findSpawnSpot();
// A buzz from the side where the bee will appear
playSound('buzz', nextBee.x);
}A hit works the same way. When a bee hits you and you still have lives left, hitPlayer() plays the hit sound from the spot where your bee is. When you lose your last life, the game over tune plays instead:
lives--;
if (lives == 0) {
changeState(states.gameover);
return;
}
playSound('hit', player.x);Put on your headphones and try it below, with Stereo panning off and on:
Don't play too many sounds at once
In your game, every bump between two bees plays a sound. With 25 bees in the swarm, that's a lot of bumps. In the demo below, bees hitting the walls make a sound too. With Sound limit off, click the canvas and listen:
That's not a swarm of bees anymore. That's hail on a tin roof. Dozens of sounds a second pile up on top of each other, and together they can get way too loud.
So don't let the same sound play again within a tenth of a second. Keep track of when each sound is allowed to play again:
// When each sound can play again, in seconds
let soundReadyAt = {};
// At the start of playSound():
let now = audioContext.currentTime;
// Skip it if it didn't load, or if it played a moment ago
if (!sounds[name] || now < (soundReadyAt[name] || 0)) {
return;
}
soundReadyAt[name] = now + 0.1;audioContext.currentTime is the AudioContext's clock, in seconds. The first time a sound plays, soundReadyAt[name] doesn't exist yet. The || 0 turns that into 0, so the sound plays. Turn Sound limit on in the demo, and you'll hear no more than ten bumps a second. That's still enough to hear the swarm.
One more rule: bumps only make a sound while you're playing. The bees also bump into each other on the start screen, and you'd hear that noise nonstop until you start a game. The bees bounce off each other in detectCollisions(), which you wrote in the tutorial about collision detection. Add the sound right where obj1 and obj2 bump into each other:
// Both bees feel the bump
obj1.bump();
obj2.bump();
// And you hear it, but only while you're playing
if (state == states.playing) {
playSound('bump', obj1.x);
}Make sound effects without audio files
You don't always need a sound file. An OscillatorNode makes a tone all by itself, just like the sound chips in old game consoles. That's handy for a quick beep while you're still looking for the right sound:
function playBeep() {
let now = audioContext.currentTime;
// A tone that slides up from 440 to 880 Hz
let oscillator = audioContext.createOscillator();
oscillator.type = 'square';
oscillator.frequency.setValueAtTime(440, now);
oscillator.frequency.exponentialRampToValueAtTime(
880, now + 0.2
);
// Start loud and fade out quickly
let gain = audioContext.createGain();
gain.gain.setValueAtTime(0.3, now);
gain.gain.exponentialRampToValueAtTime(0.001, now + 0.2);
oscillator.connect(gain);
gain.connect(masterGain);
oscillator.start(now);
oscillator.stop(now + 0.2);
}type is the shape of the wave. 'sine' sounds soft, 'triangle' a little brighter, and 'square' and 'sawtooth' give you the buzzy sound of a retro game. frequency is the pitch. exponentialRampToValueAtTime() slides it to another value, which sounds like a jump in a platform game when it goes up, and like a laser when it goes down.
The gain fades the tone out, so it doesn't end with a click. An exponential ramp can't reach exactly 0, so it goes to 0.001.
Try it yourself. Click on the left for a low tone and on the right for a high one, at the top for a tone that slides up and at the bottom for one that slides down:
let now = audioContext.currentTime;
let oscillator = audioContext.createOscillator();
oscillator.type = 'square';
oscillator.frequency.setValueAtTime(440, now);
oscillator.frequency.exponentialRampToValueAtTime(
880, now + 0.2
);The sound effects in this game were made the same way, from simple waves like these, and then saved as MP3 files.
Find sounds for your game
Don't feel like making your own sounds? There are plenty of free ones. Here are a few good places to start:
- Pixabay - Thousands of sound effects, from coins to thunder, plus music. They're free to use, even in a game you sell, and credit is optional.
- Kenney - Hundreds of sounds made for games, from clicks to explosions. They're all free to use, and you don't have to credit anyone.
- Freesound - A huge library of recorded sounds, from footsteps to birds. Filter by license to find the ones you can use freely.
Always check the license. CC0 means you can use a sound for anything, without asking and without giving credit. CC BY means you can use it too, as long as you credit the creator, for example in your game's credits. Other licenses may not let you use a sound in a game you sell, so read them carefully.
Keep your files small so your game loads fast. A short sound effect is only a few kilobytes as an MP3. Music is a lot bigger: the 26-second loop in the bee game takes up just over 400 KB. A short piece that loops well is enough for most games.
Got a WAV file? Convert it to MP3 first, because a WAV file is about ten times bigger. You can do that in Audacity, a free sound editor for Windows, Mac and Linux. Audacity is also handy for cutting a sound to the right length. Trim the silence at the start too, so the sound plays the moment you need it.
Play the finished game
That's everything you need. Your game now has sound effects, music that gets softer when you pause and a mute button that remembers your choice. The complete code is further down. Turn your sound on, then click or tap the canvas below to start:
Press M or click the speaker to turn the sound off. Did you swap in your own sounds? Tell us about it in the comments below.
Common questions about game audio
Why is there no sound on my iPhone?
Check whether your iPhone is in silent mode. You turn that on and off with the switch or the Action button on the side. In silent mode, Safari mutes the Web Audio API, while a video still plays with sound. Set navigator.audioSession.type to 'playback' in createAudio(), before you create the AudioContext, and your game's sound plays like a video's, even in silent mode. Check that navigator.audioSession exists first, because only Safari has it. The downside is that this setting pauses music from other apps, just like a video does. The demos on this page use it. The complete code doesn't, so you can decide for your own game.
Why can't fetch() load my sound files when I open the HTML file directly?
When you open a file straight from your computer, its address starts with file://. For security reasons, browsers don't let a page opened that way use fetch() to load other files on your computer. Run a small local server instead, like the Live Server extension in VS Code, or npx serve in your game's folder. Files from a website are a different story: fetch() can load them if the website allows it, and spicyyoghurt.com does. That's why the complete code on this page works, even when you open it straight from your computer.
Should I use a library like Howler.js?
Howler.js wraps the Web Audio API in a simple interface and handles a few browser quirks for you. For a small game, the code on this page is all you need, and you know exactly what happens. For a big game with lots of sounds, a library can save you time.
Which audio format works in every browser?
MP3. Every browser can decode it, on computers and phones. Ogg and Opus files are smaller at the same quality, but some older iPhones and Macs can't play them. WAV works everywhere too, but it's big, so only use it for very short sounds.
Why is there a delay before my sound plays?
With an audio element, the browser often has to load and prepare the file first. Load your sounds with the Web Audio API before the game starts, as the code on this page does, and they're ready in memory. Part of the delay can also be in the file itself, because many sound files start with a bit of silence. Trim it in a sound editor like Audacity.
How do I fade the music in or out?
Use linearRampToValueAtTime() on the music's gain. Set the current volume with setValueAtTime() first, then ramp it to 0 over a second or two. Stop the music when the fade is done, for example with music.stop(now + 2). For a fade-in, do the opposite: start at 0 and ramp up to the volume you want.
The complete code
Here's the complete code for the game. It picks up where the game states tutorial left off, and it loads the sprite sheet and the sounds from spicyyoghurt.com. Paste it into an HTML file and open it in your browser:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Game Audio Tutorial | Spicy Yoghurt</title>
<style>
#canvas {
width: 750px;
height: 400px;
border: 1px solid lightgray;
}
</style>
</head>
<body>
<h1>Game audio tutorial by Spicy Yoghurt</h1>
<canvas
id="canvas"
width="750"
height="400"
tabindex="0"
>
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
'use strict';
// Define the edges of the canvas
const canvasWidth = 750;
const canvasHeight = 400;
// The sprite sheet of the bee
const spriteUrl =
'https://spicyyoghurt.com/img/tutorials/' +
'develop_a_html5_game/bee-sprite-sheet.png';
// The sound files, with a volume for each sound and how much
// its pitch can vary every time it plays (0.1 is 10%)
const soundUrl =
'https://spicyyoghurt.com/img/tutorials/' +
'develop_a_html5_game/';
const soundFiles = {
start: {file: 'bee-start.mp3', volume: 0.5, vary: 0},
hit: {file: 'bee-hit.mp3', volume: 0.7, vary: 0.1},
buzz: {file: 'bee-buzz.mp3', volume: 0.4, vary: 0.1},
bump: {file: 'bee-bump.mp3', volume: 0.3, vary: 0.15},
gameOver: {file: 'bee-game-over.mp3', volume: 0.6, vary: 0},
best: {file: 'bee-best.mp3', volume: 0.6, vary: 0},
music: {file: 'bee-music.mp3', volume: 0.35, vary: 0}
};
let canvas;
let context;
let oldTimeStamp = 0;
let gameObjects = [];
let player;
// The game keys, by event.code
const gameKeys = [
'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight',
'KeyW', 'KeyA', 'KeyS', 'KeyD', 'Space'
];
// The keys that are down right now
let keys = {};
// The mouse or finger on the canvas
let pointer = {x: 0, y: 0, isDown: false};
// How many seconds the game has been in this state
let stateTime = 0;
let score = 0;
let lives = 3;
let highScore = 0;
let isNewHighScore = false;
// A new bee joins the swarm every few seconds
const maxBees = 25;
let spawnInterval = 5;
let spawnTimer = 5;
// The spot where the next bee will appear
let nextBee = null;
// The pause button, to the left of the mute button
const pauseButton = {x: 646, y: 14, width: 40, height: 40};
// The buttons on the pause screen
const menuButtons = [
{
text: 'Resume',
x: 285, y: 150, width: 180, height: 46,
onClick: resumeGame
},
{
text: 'Restart',
x: 285, y: 212, width: 180, height: 46,
onClick: startGame
},
{
text: 'Quit',
x: 285, y: 274, width: 180, height: 46,
onClick: quitGame
}
];
// The mute button in the top-right corner, on every screen
const muteButton = {x: 696, y: 14, width: 40, height: 40};
// One AudioContext for all the sound in the game
let audioContext;
let masterGain;
let musicGain;
let musicFilter;
// The decoded sounds by name, and the music that's playing
let sounds = {};
let music = null;
let isMuted = false;
// When each sound can play again, in seconds
let soundReadyAt = {};
// Every state has its own update(), draw() and controls.
// enter() and exit() run when the game switches states.
const states = {
start: {
enter() {
// Back on the start screen, the music stops
stopMusic();
},
update(secondsPassed) {
// The bees already fly around behind the title
updateObjects(secondsPassed);
},
draw() {
drawStartScreen();
},
onKeyDown(code) {
if (isStartKey(code)) {
startGame();
}
},
onPointerDown(event) {
startGame();
}
},
playing: {
enter() {
// Your finger steers the bee instead of scrolling
canvas.style.touchAction = 'none';
},
exit() {
// On every other screen, the page scrolls again
canvas.style.touchAction = 'auto';
},
update(secondsPassed) {
updateObjects(secondsPassed);
updateSpawning(secondsPassed);
// 10 points for every second you stay alive
score += 10 * secondsPassed;
},
draw() {
drawHud();
drawPauseButton();
},
onKeyDown(code) {
if (isPauseKey(code)) {
pauseGame();
}
},
onPointerDown(event) {
if (isOnButton(pauseButton)) {
pauseGame();
} else {
// Fly toward the mouse or finger while it's down
pointer.isDown = true;
canvas.setPointerCapture(event.pointerId);
}
}
},
paused: {
enter() {
// Soft, muffled music while the game is paused
muffleMusic(true);
},
exit() {
// And back to normal when the pause ends
muffleMusic(false);
},
update(secondsPassed) {
// Everything stands still
},
draw() {
drawHud();
drawPauseScreen();
},
onKeyDown(code) {
if (isPauseKey(code)) {
resumeGame();
}
},
onPointerDown(event) {
// Click a button on the pause screen
for (let i = 0; i < menuButtons.length; i++) {
if (isOnButton(menuButtons[i])) {
menuButtons[i].onClick();
}
}
}
},
gameover: {
enter() {
// Keep the best score, and save it for next time
isNewHighScore = Math.floor(score) > highScore;
if (isNewHighScore) {
highScore = Math.floor(score);
localStorage.setItem('beeHighScore', highScore);
}
// Stop the music and play a short tune
stopMusic();
playSound(isNewHighScore ? 'best' : 'gameOver');
},
update(secondsPassed) {
// Everything stands still
},
draw() {
drawHud();
drawGameOverScreen();
},
onKeyDown(code) {
// Wait a second, so you don't miss your score
if (stateTime > 1 && isStartKey(code)) {
startGame();
}
},
onPointerDown(event) {
if (stateTime > 1) {
startGame();
}
}
}
};
// The state the game is in right now
let state = states.start;
class GameObject {
constructor(context, x, y, vx, vy, mass) {
this.context = context;
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
this.mass = mass;
this.restitution = 0.9;
this.isColliding = false;
}
}
class Bee extends GameObject {
// One sprite sheet for all bees, with 4 columns and 2 rows
static sprite;
static numColumns = 4;
static numRows = 2;
static frameWidth = 128;
static frameHeight = 128;
// One animation for every row of the sprite sheet
static animations = {
fly: {row: 0, fps: 20, loop: true},
bump: {row: 1, fps: 10, loop: false}
};
constructor(context, x, y, vx, vy) {
super(context, x, y, vx, vy, 1);
// Keep flying at the same speed after a bump
this.restitution = 1;
// The hitbox is the round body of the bee
this.radius = 15;
// Face the direction of the velocity
this.angle = Math.atan2(vy, vx);
// Start at a random frame, so the bees don't flap in sync
this.animation = Bee.animations.fly;
this.currentFrame =
Math.floor(Math.random() * Bee.numColumns);
this.frameTimer = 0;
}
play(name) {
this.animation = Bee.animations[name];
this.currentFrame = 0;
this.frameTimer = 0;
}
bump() {
// Don't start over while the bee is still dizzy
if (this.animation != Bee.animations.bump) {
this.play('bump');
}
}
update(secondsPassed) {
// Move at the current velocity
this.x += this.vx * secondsPassed;
this.y += this.vy * secondsPassed;
// Calculate the angle, in radians
this.angle = Math.atan2(this.vy, this.vx);
// Pick the next frame when it's due
this.frameTimer += secondsPassed;
while (this.frameTimer >= 1 / this.animation.fps) {
this.frameTimer -= 1 / this.animation.fps;
this.currentFrame++;
if (this.currentFrame == Bee.numColumns) {
if (this.animation.loop) {
this.currentFrame = 0;
} else {
this.play('fly');
}
}
}
}
draw() {
// Save the context, move it to the bee and rotate it
this.context.save();
this.context.translate(this.x, this.y);
this.context.rotate(this.angle);
// Draw the image around (0, 0), the middle of the body
this.context.drawImage(
Bee.sprite,
this.currentFrame * Bee.frameWidth,
this.animation.row * Bee.frameHeight,
Bee.frameWidth, Bee.frameHeight,
-28, -32, 64, 64
);
// Put the context back the way it was
this.context.restore();
}
}
class Player extends Bee {
constructor(context, x, y) {
super(context, x, y, 0, 0);
// Heavier, so you push the other bees away
this.mass = 3;
// A bit bigger than the other bees, and so is the hitbox
this.scale = 1.25;
this.radius = 15 * this.scale;
// Pixels per second
this.speed = 200;
// How far the dashes of the ring have moved
this.dashOffset = 0;
// Seconds until a bee can hurt you again
this.invincibleTime = 0;
}
update(secondsPassed) {
this.invincibleTime -= secondsPassed;
// Move the dashes 20 pixels per second, so the ring turns
this.dashOffset -= 20 * secondsPassed;
// Fly in the direction of the controls
let direction = getDirection(this);
this.vx = direction.x * this.speed;
this.vy = direction.y * this.speed;
// Keep facing the same way when you stop
let angle = this.angle;
super.update(secondsPassed);
if (direction.x == 0 && direction.y == 0) {
this.angle = angle;
}
}
draw() {
// Blink after a hit, while nothing can hurt you
let blink = Math.floor(this.invincibleTime * 8) % 2;
if (this.invincibleTime > 0 && blink == 1) {
this.context.globalAlpha = 0.3;
}
// A dashed ring that turns,
// so you can spot your own bee in the swarm
this.context.strokeStyle = '#0099b0';
this.context.lineWidth = 3;
this.context.setLineDash([8, 7]);
this.context.lineDashOffset = this.dashOffset;
this.context.beginPath();
this.context.arc(this.x, this.y, 34, 0, 2 * Math.PI);
this.context.stroke();
this.context.setLineDash([]);
// Draw the bee bigger, scaled around its middle
this.context.save();
this.context.translate(this.x, this.y);
this.context.scale(this.scale, this.scale);
this.context.translate(-this.x, -this.y);
super.draw();
this.context.restore();
this.context.globalAlpha = 1;
}
}
window.onload = init;
function init() {
canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
// Set up the sound, and check if you muted it last time
createAudio();
isMuted = localStorage.getItem('beeMuted') == 'true';
masterGain.gain.value = isMuted ? 0 : 1;
// The keyboard, only when the canvas has focus
canvas.addEventListener('keydown', onKeyDown);
canvas.addEventListener('keyup', onKeyUp);
canvas.addEventListener('blur', releaseAllKeys);
canvas.focus();
// The mouse, a finger or a pen
canvas.addEventListener('pointerdown', onPointerDown);
canvas.addEventListener('pointermove', updatePointer);
canvas.addEventListener('pointerup', onPointerUp);
canvas.addEventListener('pointercancel', onPointerUp);
// Pause when you click somewhere else or switch tabs
canvas.addEventListener('blur', pauseGame);
document.addEventListener('visibilitychange', function () {
if (document.hidden) {
pauseGame();
// A hidden tab stops the game loop, but not the sound
audioContext.suspend();
} else if (state != states.start) {
audioContext.resume();
}
});
// The best score from an earlier visit, or 0
highScore = Number(localStorage.getItem('beeHighScore'));
// Show the start screen when the sprite sheet
// and the sounds have loaded
let loading = [loadImage(spriteUrl), loadSounds()];
Promise.all(loading).then(function (results) {
Bee.sprite = results[0];
resetGame();
window.requestAnimationFrame(gameLoop);
});
}
function loadImage(src) {
return new Promise(function (resolve, reject) {
let img = new Image();
img.onload = function () {
resolve(img);
};
img.onerror = reject;
img.src = src;
});
}
function createAudio() {
audioContext = new AudioContext();
// Every sound goes through the master volume to the speakers
masterGain = audioContext.createGain();
masterGain.connect(audioContext.destination);
// The music has its own volume, and a filter
// for when the game is paused
musicGain = audioContext.createGain();
musicGain.gain.value = soundFiles.music.volume;
musicFilter = audioContext.createBiquadFilter();
musicFilter.type = 'lowpass';
musicFilter.frequency.value = 20000;
musicGain.connect(musicFilter);
musicFilter.connect(masterGain);
}
function loadSound(url) {
// Download the file and decode it into an AudioBuffer
return fetch(url)
.then(function (response) {
return response.arrayBuffer();
})
.then(function (data) {
return audioContext.decodeAudioData(data);
})
.catch(function () {
// No sound, but the game still works
return null;
});
}
function loadSounds() {
let names = Object.keys(soundFiles);
let loading = names.map(function (name) {
return loadSound(soundUrl + soundFiles[name].file);
});
// Keep each decoded sound under its name
return Promise.all(loading).then(function (buffers) {
for (let i = 0; i < names.length; i++) {
sounds[names[i]] = buffers[i];
}
});
}
function playSound(name, x = canvasWidth / 2) {
let now = audioContext.currentTime;
// Skip it if it didn't load, or if it played a moment ago
if (!sounds[name] || now < (soundReadyAt[name] || 0)) {
return;
}
soundReadyAt[name] = now + 0.1;
// A new source every time, because a source only plays once
let source = audioContext.createBufferSource();
source.buffer = sounds[name];
// A slightly different pitch every time
let change = (Math.random() * 2 - 1) * soundFiles[name].vary;
source.playbackRate.value = 1 + change;
// The volume of this sound
let gain = audioContext.createGain();
gain.gain.value = soundFiles[name].volume;
// Left or right, based on where it happens on the canvas
let panner = audioContext.createStereoPanner();
panner.pan.value = (x - canvasWidth / 2) / canvasWidth;
source.connect(gain);
gain.connect(panner);
panner.connect(masterGain);
source.start();
}
function startMusic() {
// Only one track at a time, so stop the old one first
stopMusic();
if (!sounds.music) {
return;
}
music = audioContext.createBufferSource();
music.buffer = sounds.music;
music.loop = true;
music.connect(musicGain);
music.start();
}
function stopMusic() {
if (music) {
music.stop();
music = null;
}
}
function muffleMusic(isMuffled) {
let now = audioContext.currentTime;
let volume = soundFiles.music.volume;
let frequency = 20000;
// Half as loud, and only the low notes
if (isMuffled) {
volume /= 2;
frequency = 600;
}
// Change smoothly instead of all at once
musicGain.gain.setTargetAtTime(volume, now, 0.1);
musicFilter.frequency.setTargetAtTime(frequency, now, 0.1);
}
function toggleMute() {
isMuted = !isMuted;
localStorage.setItem('beeMuted', isMuted);
// Fade out quickly, so you don't hear a click
let volume = isMuted ? 0 : 1;
masterGain.gain.setTargetAtTime(
volume, audioContext.currentTime, 0.02
);
}
function resizeCanvas() {
// One canvas pixel for every pixel of the screen
let ratio = window.devicePixelRatio || 1;
canvas.width = Math.round(canvas.clientWidth * ratio);
canvas.height = Math.round(canvas.clientHeight * ratio);
// Keep drawing in game coordinates (750 x 400)
context.setTransform(
canvas.width / canvasWidth, 0,
0, canvas.height / canvasHeight,
0, 0
);
}
function resetGame() {
// Your own bee, in the middle of the canvas
player = new Player(context, 375, 200);
// A small swarm, not too close to you
gameObjects = [];
for (let i = 0; i < 6; i++) {
let spot = findSpawnSpot();
gameObjects.push(createBee(spot.x, spot.y));
}
gameObjects.push(player);
// Everything else back to how it was at the start
score = 0;
lives = 3;
isNewHighScore = false;
spawnInterval = 5;
spawnTimer = spawnInterval;
nextBee = null;
}
function findSpawnSpot() {
let x;
let y;
let dx;
let dy;
// Try random spots until one is far enough away from you
do {
x = 50 + Math.random() * 650;
y = 50 + Math.random() * 300;
dx = x - player.x;
dy = y - player.y;
} while (dx * dx + dy * dy < 200 * 200);
return {x: x, y: y};
}
function createBee(x, y) {
// Every bee flies at 100 pixels per second
let angle = Math.random() * 2 * Math.PI;
return new Bee(
context, x, y,
Math.cos(angle) * 100, Math.sin(angle) * 100
);
}
function changeState(newState) {
// Let the old state finish, and the new state begin
if (state.exit) {
state.exit();
}
state = newState;
stateTime = 0;
if (state.enter) {
state.enter();
}
}
function startGame() {
// The first click or key press also turns on the sound
audioContext.resume();
resetGame();
changeState(states.playing);
playSound('start');
startMusic();
}
function pauseGame() {
// Only a running game can be paused
if (state == states.playing) {
changeState(states.paused);
}
}
function resumeGame() {
changeState(states.playing);
}
function quitGame() {
changeState(states.start);
}
function onKeyDown(event) {
keys[event.code] = true;
// Don't let the game keys scroll the page
if (gameKeys.includes(event.code)) {
event.preventDefault();
}
// A key that you hold down only counts once
if (event.repeat) {
return;
}
// M turns the sound on and off on every screen
if (event.code == 'KeyM') {
toggleMute();
return;
}
// The current state decides what the key does
state.onKeyDown(event.code);
}
// Space or Enter starts the game
function isStartKey(code) {
return code == 'Space' || code == 'Enter';
}
// P or Escape pauses or resumes the game
function isPauseKey(code) {
return code == 'KeyP' || code == 'Escape';
}
function onKeyUp(event) {
keys[event.code] = false;
}
function releaseAllKeys() {
// The game can't see keys being released anymore
keys = {};
}
function onPointerDown(event) {
updatePointer(event);
// The mute button works on every screen
if (isOnButton(muteButton)) {
toggleMute();
return;
}
// The current state decides what the click or tap does
state.onPointerDown(event);
}
function onPointerUp() {
pointer.isDown = false;
// On a touchscreen, the browser only allows sound
// once the finger lifts off the screen
audioContext.resume();
}
function updatePointer(event) {
// The position on the canvas, in screen pixels
let rect = canvas.getBoundingClientRect();
let screenX = event.clientX - rect.left;
let screenY = event.clientY - rect.top;
// Convert it to game coordinates
pointer.x = screenX * canvasWidth / rect.width;
pointer.y = screenY * canvasHeight / rect.height;
}
function getDirection(obj) {
let x = 0;
let y = 0;
// The arrow keys or WASD
if (keys.ArrowLeft || keys.KeyA) {
x -= 1;
}
if (keys.ArrowRight || keys.KeyD) {
x += 1;
}
if (keys.ArrowUp || keys.KeyW) {
y -= 1;
}
if (keys.ArrowDown || keys.KeyS) {
y += 1;
}
// Hold the mouse or a finger down to fly toward it
if (pointer.isDown) {
x = pointer.x - obj.x;
y = pointer.y - obj.y;
// Stop when you get there
if (x * x + y * y < 10 * 10) {
x = 0;
y = 0;
}
}
// Give the direction a length of 1, so you fly
// just as fast in every direction
let length = Math.sqrt(x * x + y * y);
if (length > 0) {
x /= length;
y /= length;
}
return {x: x, y: y};
}
function isOnButton(button) {
return pointInRect(
pointer.x, pointer.y,
button.x, button.y, button.width, button.height
);
}
function pointInRect(px, py, x, y, w, h) {
return px >= x && px <= x + w && py >= y && py <= y + h;
}
function gameLoop(timeStamp) {
// Calculate how much time has passed, capped at a maximum
let secondsPassed = (timeStamp - oldTimeStamp) / 1000;
oldTimeStamp = timeStamp;
secondsPassed = Math.min(secondsPassed, 0.1);
stateTime += secondsPassed;
state.update(secondsPassed);
draw();
window.requestAnimationFrame(gameLoop);
}
function updateObjects(secondsPassed) {
// Loop over all game objects
for (let i = 0; i < gameObjects.length; i++) {
gameObjects[i].update(secondsPassed);
}
detectCollisions();
detectEdgeCollisions();
}
function updateSpawning(secondsPassed) {
// Stop when the swarm is big enough
if (gameObjects.length > maxBees) {
return;
}
// Pick a spot one second early, to warn the player
spawnTimer -= secondsPassed;
if (spawnTimer < 1 && !nextBee) {
nextBee = findSpawnSpot();
// A buzz from the side where the bee will appear
playSound('buzz', nextBee.x);
}
if (spawnTimer <= 0) {
// Add it first, so it's drawn under your bee
gameObjects.unshift(createBee(nextBee.x, nextBee.y));
nextBee = null;
// A little sooner every time, but not too fast
spawnInterval = Math.max(spawnInterval - 0.25, 2);
spawnTimer = spawnInterval;
}
}
function hitPlayer() {
// Only while playing, and not right after a hit
if (state != states.playing || player.invincibleTime > 0) {
return;
}
lives--;
if (lives == 0) {
changeState(states.gameover);
return;
}
playSound('hit', player.x);
// Two seconds to get away
player.invincibleTime = 2;
}
function draw() {
// Clear the canvas
context.clearRect(0, 0, canvas.width, canvas.height);
// Draw the warning for the next bee and all game objects
drawWarning();
for (let i = 0; i < gameObjects.length; i++) {
gameObjects[i].draw();
}
// Draw the screen of the current state on top
state.draw();
// The mute button on top of every screen
drawMuteButton();
}
function drawWarning() {
if (!nextBee) {
return;
}
// A red ring that shrinks until the bee appears
context.strokeStyle = '#ff8080';
context.lineWidth = 3;
context.beginPath();
context.arc(
nextBee.x, nextBee.y, 15 + spawnTimer * 30, 0, 2 * Math.PI
);
context.stroke();
}
function drawHud() {
// The score in the top-left corner
context.font = 'bold 24px Arial';
context.textAlign = 'left';
context.textBaseline = 'middle';
context.fillStyle = '#303030';
context.fillText('Score: ' + Math.floor(score), 20, 30);
// A small bee for every life you have left
for (let i = 0; i < lives; i++) {
context.drawImage(
Bee.sprite,
0, 0, Bee.frameWidth, Bee.frameHeight,
8 + i * 40, 42, 52, 52
);
}
}
function drawPauseButton() {
// Two bars, the symbol for pause
let x = pauseButton.x;
let y = pauseButton.y;
context.fillStyle = '#303030';
context.fillRect(x + 10, y + 8, 7, 24);
context.fillRect(x + 23, y + 8, 7, 24);
}
function drawMuteButton() {
let x = muteButton.x;
let y = muteButton.y;
// White on the dark screens, dark on the others
let isDark =
state == states.paused || state == states.gameover;
context.fillStyle = isDark ? 'white' : '#303030';
context.strokeStyle = context.fillStyle;
context.lineWidth = 3;
// A speaker
context.beginPath();
context.moveTo(x + 6, y + 15);
context.lineTo(x + 13, y + 15);
context.lineTo(x + 22, y + 7);
context.lineTo(x + 22, y + 33);
context.lineTo(x + 13, y + 25);
context.lineTo(x + 6, y + 25);
context.closePath();
context.fill();
if (isMuted) {
// An X: the sound is off
context.beginPath();
context.moveTo(x + 27, y + 14);
context.lineTo(x + 37, y + 26);
context.moveTo(x + 37, y + 14);
context.lineTo(x + 27, y + 26);
context.stroke();
} else {
// Two waves: the sound is on
context.beginPath();
context.arc(x + 22, y + 20, 8, -0.8, 0.8);
context.stroke();
context.beginPath();
context.arc(x + 22, y + 20, 14, -0.8, 0.8);
context.stroke();
}
}
function drawText(text, x, y, font) {
context.font = font;
context.textAlign = 'center';
context.textBaseline = 'middle';
context.fillText(text, x, y);
}
function drawStartScreen() {
// A light layer, so the text stands out from the bees
context.fillStyle = 'rgba(255, 255, 255, 0.6)';
context.fillRect(0, 0, canvasWidth, canvasHeight);
context.fillStyle = '#303030';
drawText('Pollen Rush', 375, 130, 'bold 48px Arial');
drawText('Best: ' + highScore, 375, 320, '18px Arial');
// Fade the text in and out, once every second
let pulse = Math.sin(stateTime * 2 * Math.PI);
context.globalAlpha = 0.6 + 0.4 * pulse;
drawText('Click to start', 375, 270, '24px Arial');
context.globalAlpha = 1;
}
function drawPauseScreen() {
// Darken the game behind the menu
context.fillStyle = 'rgba(0, 0, 0, 0.5)';
context.fillRect(0, 0, canvasWidth, canvasHeight);
context.fillStyle = 'white';
drawText('Paused', 375, 100, 'bold 40px Arial');
for (let i = 0; i < menuButtons.length; i++) {
drawButton(menuButtons[i]);
}
}
function drawButton(button) {
// Lighter when the mouse is over it
context.fillStyle = isOnButton(button)
? '#33b5c7'
: '#0099b0';
context.fillRect(
button.x, button.y, button.width, button.height
);
context.fillStyle = 'white';
drawText(
button.text,
button.x + button.width / 2, button.y + button.height / 2,
'22px Arial'
);
}
function drawGameOverScreen() {
// Darken the game behind the text
context.fillStyle = 'rgba(0, 0, 0, 0.5)';
context.fillRect(0, 0, canvasWidth, canvasHeight);
context.fillStyle = 'white';
drawText('Game over', 375, 120, 'bold 48px Arial');
drawText(
'Score: ' + Math.floor(score), 375, 185, '28px Arial'
);
if (isNewHighScore) {
drawText('New best!', 375, 225, 'bold 22px Arial');
} else {
drawText('Best: ' + highScore, 375, 225, '22px Arial');
}
// A click only starts a new game after a second
if (stateTime > 1) {
drawText('Click to play again', 375, 300, '24px Arial');
}
}
function detectCollisions() {
let obj1;
let obj2;
// Reset the collision state of all objects
for (let i = 0; i < gameObjects.length; i++) {
gameObjects[i].isColliding = false;
}
// Start checking for collisions
for (let i = 0; i < gameObjects.length; i++) {
obj1 = gameObjects[i];
for (let j = i + 1; j < gameObjects.length; j++) {
obj2 = gameObjects[j];
// Compare object1 with object2
if (!circleIntersect(
obj1.x, obj1.y, obj1.radius,
obj2.x, obj2.y, obj2.radius
)) {
continue;
}
obj1.isColliding = true;
obj2.isColliding = true;
// A bee that touches you costs a life
if (obj1 == player || obj2 == player) {
hitPlayer();
}
// Find the direction of the collision
let vCollision = {
x: obj2.x - obj1.x,
y: obj2.y - obj1.y
};
let distance = Math.sqrt(
(obj2.x - obj1.x) * (obj2.x - obj1.x) +
(obj2.y - obj1.y) * (obj2.y - obj1.y)
);
// Two objects in the same spot have no direction
if (distance == 0) {
continue;
}
let vCollisionNorm = {
x: vCollision.x / distance,
y: vCollision.y / distance
};
// Push them apart, so they don't sink into each other
separate(obj1, obj2, vCollisionNorm, distance);
// Calculate the speed of the detected collision
let vRelativeVelocity = {
x: obj1.vx - obj2.vx,
y: obj1.vy - obj2.vy
};
let speed =
vRelativeVelocity.x * vCollisionNorm.x +
vRelativeVelocity.y * vCollisionNorm.y;
// The objects are already moving apart
if (speed < 0) {
continue;
}
// Use the lower restitution of the two objects
let restitution = Math.min(
obj1.restitution, obj2.restitution
);
// Change the velocity of both objects
let totalMass = obj1.mass + obj2.mass;
let impulse = (1 + restitution) * speed / totalMass;
obj1.vx -= (impulse * obj2.mass * vCollisionNorm.x);
obj1.vy -= (impulse * obj2.mass * vCollisionNorm.y);
obj2.vx += (impulse * obj1.mass * vCollisionNorm.x);
obj2.vy += (impulse * obj1.mass * vCollisionNorm.y);
// Both bees feel the bump
obj1.bump();
obj2.bump();
// And you hear it, but only while you're playing
if (state == states.playing) {
playSound('bump', obj1.x);
}
}
}
}
function circleIntersect(x1, y1, r1, x2, y2, r2) {
// Calculate the squared distance between the two centers
let squareDistance =
(x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
// When the distance is less than or equal to the sum
// of the two radii, the circles touch or overlap
return squareDistance <= ((r1 + r2) * (r1 + r2));
}
function separate(obj1, obj2, vCollisionNorm, distance) {
// How far the circles overlap
let overlap = obj1.radius + obj2.radius - distance;
// Move them apart along the collision normal
let totalMass = obj1.mass + obj2.mass;
obj1.x -= vCollisionNorm.x * overlap * obj2.mass / totalMass;
obj1.y -= vCollisionNorm.y * overlap * obj2.mass / totalMass;
obj2.x += vCollisionNorm.x * overlap * obj1.mass / totalMass;
obj2.y += vCollisionNorm.y * overlap * obj1.mass / totalMass;
}
function detectEdgeCollisions() {
let obj;
for (let i = 0; i < gameObjects.length; i++) {
obj = gameObjects[i];
// Check for left and right
if (obj.x < obj.radius) {
obj.vx = Math.abs(obj.vx) * obj.restitution;
obj.x = obj.radius;
obj.bump();
} else if (obj.x > canvasWidth - obj.radius) {
obj.vx = -Math.abs(obj.vx) * obj.restitution;
obj.x = canvasWidth - obj.radius;
obj.bump();
}
// Check for top and bottom
if (obj.y < obj.radius) {
obj.vy = Math.abs(obj.vy) * obj.restitution;
obj.y = obj.radius;
obj.bump();
} else if (obj.y > canvasHeight - obj.radius) {
obj.vy = -Math.abs(obj.vy) * obj.restitution;
obj.y = canvasHeight - obj.radius;
obj.bump();
}
}
}
</script>
</body>
</html>What's next?
Your bee game now has sound. Sound effects play right away and overlap, the music loops and gets softer in the pause menu, and the mute button remembers your choice. You've learned how to load sounds with fetch(), turn the sound on when the player first clicks, and use audio nodes for volume, pitch and stereo panning.
If you have any questions, feel free to ask them in the comment section. You can download the example code here.
Up next: Finish and publish your HTML5 game
In the last part of this series, you'll play a more polished version of your bee game and learn how to publish it on the web, in the app stores and on Steam.
Comments
Thanks! We've received your comment. We check every comment by hand before it appears, so this can take a few days.

No comments yet. Be the first to leave one!