HTML and CSS Reference
In-Depth Information
Gravity
In this section, we look at simple gravity as seen from the earth's surface, and as described in Chapter 5.
In this case, gravity works pretty much the same in 3D as it does in 2D. Choose a number for the force
gravity that is exerting on the object, and add that number to the object's y velocity on each animation
frame.
Gravity in 3D may be simple, but something simple can create a great looking effect. In this example, we
combine gravity with bouncing to give the appearance of dumping a bucket of tiny rubber bouncy balls
onto the floor.
You need an object to represent a single rubber bouncy ball, so we again use the Ball3d class, but with a
smaller radius. Make each ball a random color, and it also helps to change the background color to black.
Here's the code for exercise, 07-bouncy-balls.html :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Fireworks</title>
<link rel="stylesheet" href="style.css">
<style>
#canvas {
background-color: #000000;
}
</style>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script src="utils.js"></script>
<script src="ball3d.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
balls = [],
numBalls = 100,
fl = 250,
vpX = canvas.width / 2,
vpY = canvas.height / 2,
gravity = 0.2,
floor = 200,
bounce = -0.6;
for (var ball, i = 0; i < numBalls; i++) {
ball = new Ball3d(3, Math.random() * 0xffffff);
ball.ypos = -100;
ball.vx = Math.random() * 6 - 3;
ball.vy = Math.random() * 6 - 3;
ball.vz = Math.random() * 6 - 3;
balls.push(ball);
}
 
Search WWH ::




Custom Search