HTML and CSS Reference

In-Depth Information

Sometimes the balls will still stick together. This is a common problem

when creating collisions among balls. This happens when balls overlap

one another before the collision test, and the reaction bounce is not

enough to split them apart completely. We have made every attempt to

optimize this function for the canvas, but we are sure further optimiza-

tions are possible.

The
collideBalls()
function takes two parameters:
ball1
and
ball2
. Both parameters

are the
ball
objects that we want to make collide:

function collideBalls(ball1,ball2) {

First, we need to calculate the difference between the center points of each ball. We

store this as
dx
and
dy
(difference x and difference y). This should look familiar because

we did something similar when we tested for a collision between the balls. The differ-

ence is that now we know they have collided, and we want to know how that collision

occurred:

var dx = ball1.nextx - ball2.nextx;

var dy = ball1.nexty - ball2.nexty;

To do this, we need to find the angle of the collision using the
Math.atan2()
function.

This function gives us the angle in radians of the collisions between the two balls. This

is the line of action or angle of collision. We need this value so that we can determine

how the balls will react when they collide:

var collisionAngle = Math.atan2(dy, dx);

Next, we calculate the velocity vector for each ball given the
x
and
y
velocities that

existed before the collision occurred:

var speed1 = Math.sqrt(ball1.velocityx * ball1.velocityx +

ball1.velocityy * ball1.velocityy);

var speed2 = Math.sqrt(ball2.velocityx * ball2.velocityx +

ball2.velocityy * ball2.velocityy);

Then, we calculate angles (in radians) for each ball given its current velocities:

var direction1 = Math.atan2(ball1.velocityy, ball1.velocityx);

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 we can bounce the balls, similar to how we bounced balls

off the sides of the canvas:

var velocityx_1 = speed1 * Math.cos(direction1 - collisionAngle);

var velocityy_1 = speed1 * Math.sin(direction1 - collisionAngle);

var velocityx_2 = speed2 * Math.cos(direction2 - collisionAngle);

var velocityy_2 = speed2 * Math.sin(direction2 - collisionAngle);