HTML and CSS Reference
InDepth Information
Ball collisions in depth
So now we get to the most interesting code of this example. We are going to update the prop
erties of each ball so that they appear to bounce off one another. Recall that we use the
nextx
and
nexty
properties because we want to make sure to test where the balls will be after they
aredrawnâ€”notwheretheyarerightnow.Thishelpskeeptheballsfromoverlappinginaway
that will make them stick together.
NOTE
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 optimizations are possible.
The
collideBalls()
function takes two parameters:
ball1
and
ball2
. Both parameters are
the
ball
objects that we want to make collide:
function
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 whenwetested foracollision between theballs. Thedifference isthat now
we know they have collided, and we want to know how that collision occurred:
var
var
dx
=
ball1
.
nextx

ball2
.
nextx
;
var
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
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
var
speed1
=
Math
.
sqrt
(
ball1
.
velocityx
*
ball1
.
velocityx
+
ball1
.
velocityy
*
ball1
.
velocityy
);
var
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: