HTML and CSS Reference
In-Depth Information
willdothiswithacalltoanewfunctionnamed canStartHere() .If canStartHere() returns
true , we drop out of the while() loop; if not, we start all over again:
placeOK = canStartHere ( tempBall );
}
The canStartHere() functionisverysimple.Itlooksthroughthe ball array,testingthenew
tempBall against all existing balls to see whether they overlap. If they do, the function re-
turns false ;ifnot,itreturns true .Totesttheoverlap,wehavecreated anothernewfunction:
hitTestCircle() :
function
function canStartHere ( ball ) {
var
var retval = true
true ;
for
for ( var
var i = 0 ; i < balls . length ; i ++ ) {
iif ( hitTestCircle ( ball , balls [ i ])) {
retval = false
false ;
}
}
return
return retval ;
}
Circle collision detection
The hitTestCircle() functionperformsacircle/circlecollision-detectiontesttoseewhether
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 oc-
curs. (Again, if we test after by using the current x and y locations, there is a good chance the
ballswillgetstucktogether andspinoutofcontrol.)Wethencompare that distance valueto
the sum of the radius of each ball. If the distance is less than or equal to the sum of the radii,
we have a collision. This is a very simple and efficient way to test collisions, and it works
especially well with collisions among balls in 2D:
function
function hitTestCircle ( ball1 , ball2 ) {
var
var retval = false
false ;
var
var dx = ball1 . nextx - ball2 . nextx ;
var
var dy = ball1 . nexty - ball2 . nexty ;
var
var distance = ( dx * dx + dy * dy );
iif ( distance <= ( ball1 . radius + ball2 . radius ) *
( ball1 . radius + ball2 . radius ) ) {
retval = true
true ;
}
Search WWH ::




Custom Search