HTML and CSS Reference
In-Depth Information
We take the mass values of each ball and update their x and y velocities based on the
law of conservation of momentum. To find the final velocity for both balls, we use the
following formulas:
velocity1 = ((mass1 - mass2) * velocity1 + 2*mass2 * velocity2) / mass1 + mass2
velocity2 = ((mass2 - mass1) * velocity2 + 2*mass1 * velocity1)/ mass1+ mass2
Actually, only the x velocity needs to be updated; the y velocity remains constant:
var final_velocityx_1 = ((ball1.mass - ball2.mass) * velocityx_1 +
(ball2.mass + ball2.mass) * velocityx_2)/(ball1.mass + ball2.mass);
var final_velocityx_2 = ((ball1.mass + ball1.mass) * velocityx_1 +
(ball2.mass - ball1.mass) * velocityx_2)/(ball1.mass + ball2.mass);
var final_velocityy_1 = velocityy_1;
var final_velocityy_2 = velocityy_2
After we have our final velocities, we rotate our angles back again so that the collision
angle is preserved:
ball1.velocityx = Math.cos(collisionAngle) * final_velocityx_1 +
Math.cos(collisionAngle + Math.PI/2) * final_velocityy_1;
ball1.velocityy = Math.sin(collisionAngle) * final_velocityx_1 +
Math.sin(collisionAngle + Math.PI/2) * final_velocityy_1;
ball2.velocityx = Math.cos(collisionAngle) * final_velocityx_2 +
Math.cos(collisionAngle + Math.PI/2) * final_velocityy_2;
ball2.velocityy = Math.sin(collisionAngle) * final_velocityx_2 +
Math.sin(collisionAngle + Math.PI/2) * final_velocityy_2;
Now, we update nextx and nexty for both balls so can use those values in the ren
der() function—or, for another collision:
ball1.nextx = (ball1.nextx += ball1.velocityx);
ball1.nexty = (ball1.nexty += ball1.velocityy);
ball2.nextx = (ball2.nextx += ball2.velocityx);
ball2.nexty = (ball2.nexty += ball2.velocityy);
}
If this is confusing to you, you are not alone. It took some serious effort
for us to translate this code from other sources into a working example
on HTML5 Canvas. The code here is based on “ Flash Lite Effort -
Embedded Systems and Pervasive Computing Lab ” by Felipe Sampaio,
available here: http://wiki.forum.nokia.com/index.php/Collision_for
_Balls . It is also partly based on Jobe Makar and Ben Winiarczyk's work
in Macromedia Flash MX 2004 Game Design Demystified , and Keith
Peters' topics on ActionScript animation.
Here is the full code listing for Example 5-7 .
Example 5-7. Balls with simple interactions
<!doctype html>
<html lang="en">
<head>
Search WWH ::




Custom Search