HTML and CSS Reference

In-Depth Information

Now, we need to make a dynamic object out of the values we just created and place

that object into the
tempBall
variable. This is where we create a
mass
property for each

ball. Again, we do this so that we can calculate the effect when the balls hit one another.

For all the balls in this example, the
mass
will be the same—the value of
tempRadius
.

We do this because, in our 2D environment, the relative size of each ball is a very simple

way to create a value for
mass
. Since the
mass
and
speed
of each ball will be the same,

they will affect each other in a similar way. Later, we will show you what happens when

we create ball objects with different
mass
values.

Finally, we create
nextX
and
nextY
properties that are equal to
x
and
y
. We will use these

values as “look ahead” properties to help alleviate collisions that occur “between” our

iterations, which lead to overlapping balls and other oddities:

tempBall = {x:tempX,y:tempY, nextX: tempX, nextY: tempY, radius:tempRadius,

speed:tempSpeed, angle:tempAngle, velocityx:tempvelocityx,

velocityy:tempvelocityy, mass:tempRadius};

Now that we have our new dynamic ball object represented by the
tempBall
variable,

we will test to see whether it can be placed at the
tempX
and
tempY
we randomly created

for it. We will do this with a call to a new function named
canStartHere()
. If
can

StartHere()
returns
true
, we drop out of the
while()
loop; if not, we start all over again:

placeOK = canStartHere(tempBall);

}

The
canStartHere()
function is very simple. It looks through the
ball
array, testing the

new
tempBall
against all existing balls to see whether they overlap. If they do, the func-

tion returns
false
; if not, it returns
true
. To test the overlap, we have created another

new function:
hitTestCircle()
:

function canStartHere(ball) {

var retval = true;

for (var i = 0; i <balls.length; i++) {

if (hitTestCircle(ball, balls[i])) {

retval = false;

}

}

return retval;

}

Circle collision detection

The
hitTestCircle()
function performs a circle/circle collision-detection test to see

whether the two circles (each representing a ball) passed as parameters to the function

are touching. Because we have been tracking the balls by the center
x
and
y
of their

location, this is quite easy to calculate. First, the function finds the distance of the line

that connects the center of each circle. We do this using our old friend the Pythagorean

theorem (A
2
+B
2
= C
2
). We use the
nextx
and
nexty
properties of the ball because we

want to test the collision before it occurs. (Again, if we test after by using the current

x
and
y
locations, there is a good chance the balls will get stuck together and spin out