HTML and CSS Reference
In-Depth Information
ax = 0;
ay = 0;
}, false);
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
vx += ax;
vy += ay;
ball.x += vx;
ball.y += vy;
ball.draw(context);
}());
};
</script>
</body>
</html>
Notice that we moved the left/right/up/down checks into a switch statement, because all of the if
statements were too much.
Play around with this one for a while. You see that you can now navigate all over the canvas. Try to get the
object moving, say, left to right, and then press the up key. Note that the x velocity is not affected at all.
The object keeps moving on the x axis at the same rate. You added some y velocity into the picture. This
is equivalent to the spaceship turning 90 degrees and firing the rockets.
Gravity as acceleration
So far, we've been talking about acceleration in terms of a force applied to an object by the object itself,
such as a car engine or a rocket. That's certainly valid, but there's another aspect to acceleration. It
happens that any force that acts to change the velocity of an object uses the principle of acceleration. This
includes such things as gravity, magnetism, springs, rubber bands, and so on.
You can look at gravity in a couple of ways. From the wide-angle perspective of the solar system, gravity is
an attraction between two bodies. The distance and angle between those two bodies must be taken into
account to figure the actual acceleration on each body.
The other way to look at gravity is from a close-up viewpoint, here on earth, or very near it. In our everyday
existence, gravity does not noticeably change depending on our distance from the earth. Although
technically speaking, the force of gravity is slightly less when you fly in a plane or up on a mountain, it's
nothing you notice. So, when simulating gravity on this level, you can define it as a set value, as you saw
in the earlier examples with the acceleration variables.
Also, because the earth is so large and we are so small, it's easy to ignore any actual direction of
acceleration and just say that the direction is “down.” In other words, no matter where your object is, you
can safely define gravity as acceleration on the y axis alone.
To put it into code, all you need to do is define a value for the force of gravity and add it to the vy on each
frame. Generally speaking, a fraction works well, something like 0.1 or below. Much more than that, and
things “feel” too heavy. With smaller values, things seem to float like feathers. Of course, you can always
 
Search WWH ::




Custom Search