HTML and CSS Reference
In-Depth Information
var
var direction1 = Math . atan2 ( ball1 . velocityy , ball1 . velocityx );
var
var direction2 = Math . atan2 ( ball2 . velocityy , ball2 . velocityx );
Next we need to rotate the vectors counterclockwise so that we can plug those values into the
equation for conservation of momentum. Basically, we are taking the angle of collision and
making it flat so that we can bounce the balls, similar to how we bounced balls off the sides
of the canvas:
var
var velocityx_1 = speed1 * Math . cos ( direction1 - collisionAngle );
var
var velocityy_1 = speed1 * Math . sin ( direction1 - collisionAngle );
var
var velocityx_2 = speed2 * Math . cos ( direction2 - collisionAngle );
var
var velocityy_2 = speed2 * Math . sin ( direction2 - collisionAngle );
We take the mass values of each ball and update their x and y velocities based on the law of
conservationofmomentum.Tofindthefinalvelocityforbothballs,weusethefollowingfor-
mulas:
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
var final_velocityx_1 = (( ball1 . mass - ball2 . mass ) * velocityx_1 +
( ball2 . mass + ball2 . mass ) * velocityx_2 ) / ( ball1 . mass + ball2 . mass );
var
var final_velocityx_2 = (( ball1 . mass + ball1 . mass ) * velocityx_1 +
( ball2 . mass - ball1 . mass ) * velocityx_2 ) / ( ball1 . mass + ball2 . mass );
var
var final_velocityy_1 = velocityy_1 ;
var
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 that we can use those values in the
render() functionâ€”or for another collision:
ball1 . nextx = ( ball1 . nextx += ball1 . velocityx );
ball1 . nexty = ( ball1 . nexty += ball1 . velocityy );
Search WWH ::

Custom Search