Making Asteroid Dodger with JavaScript and HTML5 Canvaswith Ted Zhu

Add Collision Detection

In this module, we're going to add logic to detect when these two events occur:

  1. The SpaceShip has been hit by an Asteroid.
  2. An Asteroid has been hit by a Bullet.

If the SpaceShip has been hit by an Asteroid, we reset the game. If an Asteroid has been hit by a Bullet, we will remove both the Asteroid and the Bullet from the canvas and let the game continue.

First, let's modify main.js so that we have two new functions: newGame() and endGame(). Note: We'll be moving a lot of the code from init() into newGame() so be sure to use cut/copy/paste. See the lines indicated in yellow:

File: main.js

Now, add an object method to the Asteroid class called collidesWith(), and a class method collidesWithAny(), as indicated in yellow:

File: asteroid.js

Now, modify the Bullet class to detect if it ever hits an asteroid:

File: bullet.js

Then, modify the SpaceShip class so that it detects if it's colliding with an Asteroid:

File: spaceship.js

If you made the code modification correctly, when you refresh the browser, you should see that you can annihilate asteroids with your bullets, and that when you hit an asteroid, the game restarts:

Now, let's keep track of score.

Debugging Tips

Debugging Tips

  • All JavaScript code is case-sensitive. Make sure that every letter of your code matches the casing as seen in the instructions.
  • Keep an eye out for all symbols such as parenthesis, periods, commas, quotations, and semicolons.
  • The semicolon at the end of every JavaScript statement is the easiest symbol to forget.

Note about whitespace:

For the most part, JavaScript doesn't care about whitespace (spaces, tabs, and carriage returns). In fact, it's actually encouraged for you to use as many spaces, tabs, and carriage returns as necessary to make your code easy to read. For example:

Without Whitespace
With Whitespace

Which is easier to read?

×