HTML and CSS Reference
In-Depth Information
Distance-based collision detection
In this section, you'll abandon the geometric hit testing functions and take collision detection into your own
hands. This involves using the distance between two objects to determine whether they have collided.
As an example of this idea in the real world, let's say the center of your car is 100 feet from the center of
my car. Given this space, you know that the two cars are far enough apart that they couldn't possibly be
touching. However, if both of our cars are 6 feet wide and 12 feet long, and the center of my car is 5 feet
from the center of your car, you can be pretty certain that we're in trouble. In other words, there is no way
for the centers to be that close together without some parts of the cars touching. That's the whole concept
behind distance-based testing. You determine the minimum distance required to separate the two objects,
calculate the current distance, and compare the two. If the current distance is less than the minimum, you
know they are hitting.
And of course, there is a trade-off. Where the simplest rectangle intersection worked perfectly with
rectangles, but was less accurate using other shapes, this method works perfectly with circles. It's problem
is that non-circle shapes that appear to be touching don't register a collision because their centers are still
not close enough.
Simple distance-based collision detection
Let's start out with the ideal situation: a couple of perfectly round circles. When doing this type of collision
detection, we should measure from the exact center of the circle; we can use our Ball class for this.
Building off the first example in this chapter, create two balls and set up one of them to be dragged with
the mouse. You'll also perform your collision detection in the drawFrame function, but instead of using
utils.intersects to check for a collision, you'll be using the distance between the two balls. You should
already know how to compute the distance between two objects using the Pythagorean Theorem from
back in Chapter 3. So, you start off with something like this:
var dx = ballB.x - ballA.x,
dy = ballB.y - ballA.y,
dist = Math.sqrt(dx * dx + dy * dy);
Now you have the distance, but how do you know whether that distance is small enough to consider that a
collision has occurred? Well, take a look at the picture in Figure 9-7.
 
Search WWH ::




Custom Search