Make a 2D game with JavaScript

Coding with JavaScript

🕑 This lesson will take about 30 minutes

In this lesson, you will learn how to make your own game using JavaScript and HTML code. The game involves a player (the hero) catching an enemy (the monster) as many times as possible in a 30 second time limit. This version of the game has been modified from the tutorial at Lost Decade Games who have shared the code and encouraged users to modify and share it.

All of the JavaScript code below contains comments that explain what each part of the code does and how it works. Make sure you read the comments to understand the code and before changing any of the code. All comments in the code below start with two forward slashes eg: // this is a comment.

To get started, you will need to create two new files in your code editor:

  • An HTML file (eg. index.html)

  • A JavaScript file (eg. game.js)

You will also need to make an images folder with three images (scroll down to see the example images):

Full code

Here is the HTML and JavaScript code for the game. Don’t forget to change the ‘src’ property for the bgImage (background image), playerImage, and enemyImage image files to your own images in your own folder. Scroll down for the images used in the example.

Images

Here are the images used in this example.

Where to from here?

Here are some extra challenges for you to try:

  • Add sound effects to the game

  • Add more enemies

  • Add random enemies (more sprites)

  • Add wall/edge detection to keep the player on the canvas

  • Add high scores

  • Add obstacles/mazes

  • Add multiplayer function