HTML and CSS Reference
In-Depth Information
return (b.zpos - a.zpos);
}
function draw (ball) {
if (ball.visible) {
ball.draw(context);
}
}
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
angleX = (mouse.y - vpY) * 0.001;
angleY = (mouse.x - vpX) * 0.001;
balls.forEach(move);
balls.sort(zSort);
balls.forEach(draw);
}());
};
</script>
</body>
</html>
Here, you find both angleY and angleX , and call both rotateX and rotateY functions for each ball. The
perspective code has been moved out of the rotate functions and into its own function, setPerspective ,
since it doesn't need to be called twice. You can easily add a rotateZ function based on what you learned
and the preceding formulas.
Collision detection
The last thing to cover in this introduction to 3D is collision detection. The only feasible way of calculating
collision detection in 3D with the canvas and JavaScript is distance-based. This is not too much different
from collision detection in 2D: You find the distance between two objects (using the 3D distance formula),
and if that is less than the sum of their radii, you have a hit.
For a 3D collision detection example, we alter one of the earlier 3D bouncing examples, giving it fewer
objects and more space. First, we perform the normal 3D motion and perspective, and then do a double
iteration to compare the locations of all the balls and check for a collision. If any are less distance apart
than twice their radius, it's a hit, and we change the color of both balls to blue. Here's the code for exercise
14-collision-3d.html :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Collision 3d</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
 
Search WWH ::




Custom Search