HTML and CSS Reference
In-Depth Information
use these effects to your advantage—for example, to create simulations of different planets with varying
gravities.
This next example adds gravity. The full code for this is in 09-gravity.html , but we won't list it all out. It
has only a few differences from 08-acceleration-3.html . In addition to the document name being
changed, we added one variable to the list of variables described at the beginning of the script:
var gravity = 0.02;
And added one line to the drawFrame function:
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
vx += ax;
vy += ay;
vy += gravity;
ball.x += vx;
ball.y += vy;
ball.draw(context);
}());
We made the gravity value low so the ball doesn't go off the screen too quickly, and you can still control it
with the keys. What you created are all the physics of the old Lunar Lander game. Add in some better
graphics and a little collision detection, and you have yourself a hit! (We help you with the latter point;
graphics are up to you.)
Notice that first you add the acceleration from the key presses to the vx and vy , and then you add the
gravity to the vy . Dealing with complex systems of multiple forces winds up not being that complex. You
calculate the acceleration of each force and tack it onto the velocity. No complex averaging or factoring
happens. Each force just gets added on. When you've handled all the forces, you add the velocity to the
position. Here, you use only a couple of forces. Later in the topic, you calculate many different forces
acting on a single object.
This goes back to vector addition. If you start off with the original velocity as a vector, each acceleration,
gravity, or force is an additional vector tacked on to that velocity. When you've added all of them on, draw
a line from the beginning to the end and you have your resulting velocity. You find it's the same as if you
added on the x and y components of each force.
Now imagine that your object is a hot air balloon. You probably want to add a force called lift. This is
another acceleration on the y axis. This time, however, it's negative, or in the “up” direction. Now, you have
three forces acting on the object: the key force, gravity, and lift. If you think about it, or try it out, you see
that the lift force needs to be slightly stronger than the gravity force in order for the balloon to rise. This is
logical—if they were exactly equal, they would cancel each other out, and you'd be back to square one,
with only the key force having any effect.
Another one to try is creating some wind. Obviously, this is a force on the x axis. Depending on which
direction the wind is blowing, it can be a positive or negative force, or as you now know, a 0- or 180-
degree direction.
 
Search WWH ::




Custom Search