HTML and CSS Reference
In-Depth Information
};
</script>
</body>
</html>
All we did here is add variables for velocity on each axis and some friction. When one of the six keys is
pressed, it adds or subtracts from the appropriate velocity (remember that acceleration changes velocity).
Then it adds the velocity to the position on each axis and computes friction.
Now you have a 3D object moving with acceleration, velocity, and friction. And done quite easily.
Bouncing
For the purposes of this section, we bounce a ball off a flat surface—in other words, one that aligns
perfectly with the x, y, or z axis. This is analogous to bouncing off the sides of our canvas element you did
in 2D.
Single object bouncing
When bouncing in 3D, again you detect when the object has gone past a boundary, adjust it to touch that
boundary, and then reverse its velocity on the appropriate axis. One of the differences with 3D is in how
you decide where the boundaries are. In 2D, you generally use the canvas element or some other visible
rectangular area. In 3D, things aren't quite so simple because there is no real concept of a visible edge—
unless you draw one. You will draw in 3D in the next chapter, so for now, bounce your objects off arbitrarily
placed, invisible walls.
The boundaries are set up as before, but now you position them in 3D space, which means that they can
be negative as well as positive. And a boundary can be set up on the z-axis. For the next example, our
boundaries look like this:
var top = -100,
bottom = 100,
left = -100,
right = 100,
front = -100,
back = 100;
After determining the object's new position, check it against all six boundaries. Remember that you take
half of the object's width into account when checking for the collision, and that you already stored that
value in a property of the Ball class called radius . Here's the full code listing for 3D bouncing (document
04-bounce-3d.html ):
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Bounce 3d</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
 
Search WWH ::




Custom Search