HTML and CSS Reference
In-Depth Information
Figure 9-6. Collision detection using a circle's bounding box causes a false positive.
To use this method for more accurate collision detection, you can test several points along the shape's
outline. This gives you a more precise definition of the object boundaries, but also means the program has
to run more tests. And depending on the shape complexity, all these tests could slow down the web
browser. For example, if you had a star-shaped object, you could calculate the position its five points, and
do a hit test from another object to each of those five points. But then if you had two stars, you would need
to test each one against the other's five points. For a star, this would probably work pretty well; but a more
complex shape would obviously need more points. You can see this gets very complex and
computationally-intensive very quickly. Just two stars, and you're up to ten times the number of hit tests
you would use for the more simple method. Accuracy costs you.
If you must perform collision detection against an irregular shape, a good strategy is to break complex
shapes into smaller rectangles, and test against those. This will give you greater accuracy, but also
increase the amount of calculations, so find a balance between the two. For greater efficiency, first test
against the entire shape's bounding box, and then only if it's a hit, break the object up into smaller
rectangles to test against.
Summary of geometric hit testing
Collision detection between two irregularly shaped objects, so that if any part of one touches the other, is
not readily supported using our simple geometric methods. But there are a few options:
For roughly rectangular objects, use utils.intersects(rectA, rectB) .
For irregularly shaped objects, you either live with the inaccuracy or custom program a solution,
probably using utils.containsPoint(rect, x, y) .
Of course, the chapter is far from done yet, and there are solutions beyond what we've covered here. If
you have circular or roughly circular objects, distance-based collision detection will probably be your best
bet. You'd be surprised at how many shapes can be characterized as “roughly rectangular” or “roughly
circular”.
 
Search WWH ::




Custom Search