HTML and CSS Reference
In-Depth Information
Figure 9-5.
Collision detection with a circle's bounding box.
Hit testing an object and a point
In Chapter 7, the utility function
utils.containsPoint
was introduced, but here we will see how it relates
to hit testing; although, it's not very useful for testing for the collision between two objects. As mentioned
previously, the function takes three arguments: the first is a rectangle object with
x
,
y
,
width
, and
height
properties, and the remaining two arguments define x and y coordinates. It returns
true
or
false
,
depending if that point is hitting the rectangle in question. Here's the function again so you don't have to
look it up, but it should already be in your
utils.js
file:
utils.containsPoint = function (rect, x, y) {
return !(x < rect.x || x > rect.x + rect.width ||
y < rect.y || y > rect.y + rect.height);
};
It might be used like this when testing if point (100, 100) falls within a rectangle:
if (utils.containsPoint(rect, 100, 100)) {
//react to collision
}
But once again, we come back to the question: What constitutes a hit? And, once again, we see the
bounding box coming into play—the code only checks if the point is within an object's bounding box.
Let's do a quick test to see that in action with example
03-point-hit-test.html
: