HTML and CSS Reference
In-Depth Information
var tx = ballA.x + dx / dist * min_dist,
ty = ballA.y + dy / dist * min_dist;
Which just wiped out three calls to trigonometry functions and replaced them with two simple divisions.
You can view this example that includes all the optimization updates in document 08-bubbles-3.html ,
which can be downloaded from www.apress.com . Before you move on, take some time to play with the
springing bubbles example. You can adjust many variables, so try changing the spring, gravity, number,
and size of the balls. You might want to try adding some friction or some mouse interaction.
Important formulas in this chapter
It's time to review the two important formulas presented in this chapter.
Distance-based collision detection
//starting with objectA and objectB
//if using an object without a radius property,
//you can use width or height divided by 2
var dx = objectB.x - objectA.x,
dy = objectB.y - objectA.y,
dist = Math.sqrt(dx * dx + dy * dy);
if (dist < objectA.radius + objectB.radius) {
//handle collision
}
Multiple-object collision detection
objects.forEach(function (objectA, i) {
for (var j = i + 1; j < objects.length; j++) {
//evaluate reference using j. For example:
var objectB = objects[j];
//perform collision detection between objectA and objectB
}
});
Summary
This chapter covered just about everything you need to know about collision detection, including using
geometric ht testing methods, distance-based collision checking, and how to efficiently track collisions
among many objects. You should know the pros and cons of each method, and situations where each
works well or does not perform satisfactorily. You'll be using all of this material as you move forward in the
book, and no doubt, you'll be using it extensively in your own projects.
In the next chapter, you'll look at collisions between objects and angled surfaces, using a technique known
as coordinate rotation. This technique will also be used in Chapter 11, where you'll find out what to do to
create a realistic reaction to the collisions you learned how to detect here.
 
Search WWH ::




Custom Search