HTML and CSS Reference
In-Depth Information
You can test the geometry of each object; that is, does the shape of this object overlap the shape
of that object? We'll use the object's rectangular bounds to determine this.
You can test the distance between objects; that is, are these objects close enough for them to be
colliding? You must calculate the distance and decide when the objects are close enough.
Each method has its uses, and we'll look at both in detail in this chapter.
However, there won't be many details about what to do when you detect a collision, or, how should two
objects react when they bump into each other? That subject is covered in Chapter 11, where we discuss
the conservation of momentum.
Geometric hit testing methods
In Chapter 7, we added a getBounds method to our Ball class, something that is used a number of times
in this chapter. Just to refresh your memory, this method returns an object representing a rectangle with
properties x , y, width , and height . This rectangle designates a bounding box that contains the shape of
ball in relation to the canvas element.
Using this rectangle, we can determine if another rectangle intersects with it, or if a coordinate falls within
its area. We will use these methods to test if one object is hitting another, or if an object is hitting a specific
point.
Hit testing two objects
Now given that two objects each have a getBounds method defined, we can determine if the objects are
touching by testing if the two bounding rectangles intersect. First, we need to add the utility function
utils.intersects to our utils.js file:
utils.intersects = function (rectA, rectB) {
return !(rectA.x + rectA.width < rectB.x ||
rectB.x + rectB.width < rectA.x ||
rectA.y + rectA.height < rectB.y ||
rectB.y + rectB.height < rectA.y);
};
Nothing fancy here, just simple geometry. You call the function by passing it two rectangle arguments, it
returns true if they overlap, and false if they don't. It is invoked like this:
utils.intersects(rectA, rectB)
When testing if two bounding boxes are touching, this will usually go within an if statement, like so:
if (utils.intersects(objectA.getBounds(), objectB.getBounds()) {
//react to collision
}
In this snippet, utils.intersects will return true if there is a collision between objectA and objectB ,
and the statements within the if block will execute. This is probably the simplest method of collision
detection, and also the easiest to program.
 
Search WWH ::




Custom Search