HTML and CSS Reference
In-Depth Information
ball.vy *= bounce;
} else if (ball.y - ball.radius < 0) {
ball.y = ball.radius;
ball.vy *= bounce;
}
}
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
ball0.x += ball0.vx;
ball0.y += ball0.vy;
ball1.x += ball1.vx;
ball1.y += ball1.vy;
checkCollision(ball0, ball1);
checkWalls(ball0);
checkWalls(ball1);
ball0.draw(context);
ball1.draw(context);
}());
};
</script>
</body>
</html>
In this example, we created a rotate function that accepts a few parameters and returns an object
representing a rotated point with x and y properties. This version isn't quite as easy to read when you're
learning the principles involved, but it results in less duplicated code.
Adding More Objects
Making two balls collide and react is no easy task, but you made it. Now let's add a few more colliding
objects—say eight. It seems as if it's going to be four times more complex, but it's not. The function you
have now checks two balls at a time, but that's all you need anyway. You add more objects, move them
around, and check each one against all the others. You've already did that in the collision-detection
examples in Chapter 9. All you need to do is to plug in the checkCollision function where you would
normally do the collision detection.
For this example ( 05-multi-billiard-1.html ), start with eight balls in an array. The checkCollision
and checkWalls functions aren't listed in their entirety, but you can use the exact same ones from the
previous example:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Multi Billiard 1</title>
<link rel="stylesheet" href="style.css">
</head>
Search WWH ::




Custom Search