HTML and CSS Reference
In-Depth Information
Again, this mostly occurs when you have a lot of objects in a small space, moving at higher speeds. It also
happens if the objects already touch at the start of the animation. As you might have already seen when
testing the example, this issue crops up now and then, so it's good to know where the problem is. The
exact point is in the checkCollision function; specifically, it occurs in the following lines:
//update position
pos0.x += vel0.x;
pos1.x += vel1.x;
This assumes that the collision occurs due to only the two ball's own velocities, and that adding back on
the new velocities separates them. Most of the time, this is true. But the situations just described are
exceptions. If you run into this problem, you need something more stringent to ensure the objects are
definitely separated before moving on. Try using the following method:
//update position
var absV = Math.abs(vel0.x) + Math.abs(vel1.x),
overlap = (ball0.radius + ball1.radius) - Math.abs(pos0.x - pos1.x);
pos0.x += vel0.x / absV * overlap;
pos1.x += vel1.x / absV * overlap;
This might not be the most mathematically accurate solution, but it seems to work well. It first determines
the absolute velocity; this is the sum of the absolute values of both velocities. For instance, if one velocity
is -5 and the other is 10, the absolute values are 5 and 10, and the total is 5 + 10, or 15.
Next, it determines how much the balls actually overlap. It does this by getting their total radii and
subtracting their distance.
Then, it moves each ball a portion of the overlap, according to their percent of the absolute velocity. The
result is that the balls should be exactly touching each other, with no overlap. It's a bit more complex than
the earlier version, but it clears up the bugs.
In fact, in the next version, 06-multi-billiard-2.html , we created 15 balls, made them a bit larger,
and randomly placed them on the canvas. The ones that overlap still freak out for a few frames, but
eventually, because of this new code, they settle down. Here's the complete code listing for the example:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Multi Billiard 2</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script src="utils.js"></script>
<script src="ball.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
balls = [],
numBalls = 15,
Search WWH ::




Custom Search