Making Asteroid Dodger with JavaScript and HTML5 Canvaswith Ted Zhu

Add Some Asteroids

Because asteroids are a new type of object, we need to make a new class. Create a new file called asteroid.js and give it the following code:

File: asteroid.js

Save this file, and then open up main.js so that it can use the Asteroid class to try to render some asteroids:

File: main.js

Then, update game.html so that the new Asteroid class will be loaded:

File: game.html

HTML

Refresh the web browser, and see if an asteroid gets rendered and moves across the screen. You should see a result similar to below:

Let the Asteroids Come from Outside In

Right now, we have the asteroids randomly popping up somewhere on the canvas. What we would like is for them to start off from a random point outside of the canvas and point inwards.

For this, we're going to have the asteroid starting position be on a large circle centered on the canvas, which we'll call the starting circle. Then we'll have the asteroids point initially to the center of the canvas.

Open asteroid.js in your code editor, and add or modify the following lines of code in the Asteroid() constructor function as indicated in yellow:

File: asteroid.js

Refresh the browser window, and see if the asteroid now starts near the edge of the canvas, and moves in the direction towards the center of the canvas. The asteroids should always cross the center point of the canvas. See an example below:

Now, we can enlarge the starting circle so that the asteroids are fully outside the canvas when they start. Also, we can add some variability to the asteroid angle so that while they are pointed towards the center of the canvas, they won't necessarily cross the center point exactly.

Enlarging the Starting Circle and Adding More Asteroids

Open asteroid.js in your code editor, and modify the following lines of code as indicated in yellow:

File: asteroid.js

Then, let's modify the main.js file so that multiple asteroids are added to the canvas:

File: main.js

Refresh the web browser and see if you have multiple asteroids coming onto the canvas in increasing amounts, like shown below:

Next, let's add collision detection!

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?

×