HTML and CSS Reference
In-Depth Information
canvas.addEventListener('mousemove', drawFrame, false);
drawFrame();
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 < 60) {
log.value = "Hit!";
} else {
log.value = '';
}
ballA.draw(context);
ballB.draw(context);
}
};
</script>
</body>
</html>
When you run this, you'll notice that it doesn't matter from which angle you approach the target ball. It
doesn't register a hit until that exact point when the shapes overlap.
It's already been mentioned that hard-coding numbers into code is generally bad style. You would need to
change the code every time you had different-sized objects. Furthermore, what about the case where the
two objects are not the same size? We need to abstract this concept into some kind of formula that will fit
any situation.
Figure 9-8 shows two balls of different sizes, again, just touching. The one on the left is 60 pixels across,
and the one on the right is 40 pixels. Thus, the radius of one is 30, and the radius of the other is 20. So,
the distance between them at the moment they touch is exactly 50. Of course, in the case of the Ball
class, we've already programmed in this radius property, so we can check it directly.
Search WWH ::




Custom Search