HTML and CSS Reference
In-Depth Information
Distance = 50
Radius = 30
Radius = 20
Diameter = 60
Diameter = 40
Figure 9-8. The distance of a collision between two different-sized objects
A pattern begins to emerge. The distance is the radius of one ball, plus the radius of the other. You can
now remove all hard-coded numbers from the code and modify the drawFrame function to this (which can
be found in document 05-distance-2.html ):
function drawFrame () {
context.clearRect(0, 0, canvas.width, canvas.height);
ballB.x = mouse.x;
ballB.y = mouse.y;
var dx = ballB.x - ballA.x,
dy = ballB.y - ballA.y,
dist = Math.sqrt(dx * dx + dy * dy);
if ( dist < ballA.radius + ballB.radius ) {
log.value = "Hit!";
} else {
log.value = '';
}
ballA.draw(context);
ballB.draw(context);
}
Go ahead and change the size of one or both of the balls (remember, you can pass in a radius as the first
parameter when instantiating the object) and see that this code works, even if one circle is huge and one
circle is tiny. In fact, in the full example mentioned earlier, the balls are declared like this:
 
Search WWH ::




Custom Search