HTML and CSS Reference
In-Depth Information
arrow.rotation = angle;
vx += ax;
vy += ay;
arrow.x += vx;
arrow.y += vy;
arrow.draw(context);
}());
};
</script>
</body>
</html>
Notice that we also change the variable
speed
into
force
and make it much smaller. Because
acceleration is additive, you want to start with small amounts because it builds up quickly. Also, now
vx
and
vy
are declared at the top of the script; earlier, they were calculated newly on each frame, but now
you need to keep track of them and add or subtract from their value each time. Of course, you can do
away with the
ax
and
ay
variables here altogether and just add the result of the sine and cosine lines
directly to the velocities. Here, they are separated for clarity.
Run the example and you see the accelerating arrow swinging around a moving cursor and pointing
toward the mouse position the entire time. But look back to the first motion example you did at the
beginning of the chapter, and see just how far you've come. By learning just a couple of basic principles,
you've now created something a million times more fluid and dynamic—something that almost feels alive.
And you're not even at the end of the chapter yet!
Let's pull everything together and see how much further you can go with it.
A spaceship
We've been talking a lot about spaceships travelling from here to there. Well, with the ground you've
covered so far, you should be able to put together a reasonable spaceship simulation.
Here's the plan. The spaceship will be a class of its own that takes care of drawing itself, much like the
Arrow
or
Ball
classes you've been using. You can use the left and right keys to rotate it left and right. The
up key will act to fire the rocket. Of course, the rocket is in the back of the ship and fires straight back.
Thus, the force that the rocket applies will cause acceleration in the direction the ship is facing at that time.
Actually, what you're going to make is like the ship in the old game
Asteroids,
but without the actual
asteroids.
First, you need a ship class. Its
draw
method uses a few lines of canvas drawing API code to render four
short, white lines, as an homage to the original that we are copying. Save the following code in the file
ship.js
to import into the next example:
function Ship () {
this.x = 0;
this.y = 0;
this.width = 25;
this.height = 20;
this.rotation = 0;
this.showFlame = false;