HTML and CSS Reference
In-Depth Information
}
if (zpos > -fl) {
var scale = fl / (fl + zpos);
ball.scaleX = ball.scaleY = scale;
ball.x = vpX + xpos * scale;
ball.y = vpY + ypos * scale;
ball.visible = true;
} else {
ball.visible = false;
}
if (ball.visible) {
ball.draw(context);
}
}());
};
</script>
</body>
</html>
All of the key-handling code has been removed from the previous example, and the ball has been given a
random velocity on each axis. Now you can see the ball is definitely bouncing around, but you can't really
tell what it is bouncing against—remember that these are arbitrarily placed invisible boundaries.
Multiple object bouncing
One thing you can do to visualize the walls a little better is to fill up the space with more objects. To do
this, we need multiple instances of the Ball class. But then each instance needs its own xpos , ypos ,
zpos , and velocities on each axis as well. It can get messy keeping track of all of that in the main code, so
we'll create a new class, Ball3d , to keep track of the values for us. Save the following script to the file
ball3d.js and we'll import it into the next examples:
function Ball3d (radius, color) {
if (radius === undefined) { radius = 40; }
if (color === undefined) { color = "#ff0000"; }
this.x = 0;
this.y = 0;
this.xpos = 0;
this.ypos = 0;
this.zpos = 0;
this.vx = 0;
this.vy = 0;
this.vz = 0;
this.radius = radius;
this.mass = 1;
this.rotation = 0;
this.scaleX = 1;
this.scaleY = 1;
this.color = utils.parseColor(color);
this.lineWidth = 1;
this.visible = true;
 
Search WWH ::




Custom Search