HTML and CSS Reference
In-Depth Information
} else if (ball.nextx-ball.radius < 0 ) {
ball.velocityx = ball.velocityx*−1;
} else if (ball.nexty+ball.radius > theCanvas.height ) {
ball.velocityy = ball.velocityy*−1;
} else if(ball.nexty-ball.radius < 0) {
ball.velocityy = ball.velocityy*−1;
}
}
}
Collisions with balls
The collide() function tests to see whether any balls have hit one another. This func-
tion uses two nested loops, both iterating through the balls array to ensure we test
each ball against every other ball. We take the ball from the first loop of the balls array,
and place it into the ball variable. Then we loop through balls again, placing each ball
in the testBall variable, one at a time. When we have both ball and testBall , we make
sure they are not equal to one another. We do this because a ball will always have a
false positive collision if we test it against itself. When we are sure they are not the same
ball, we call hitTestCircle() to test for a collision. If we find one, we call collide
Balls() , and then all hell breaks loose. (OK, not really, but the balls do collide, and
some really interesting code gets executed.) See that code here:
function collide() {
var ball;
var testBall;
for (var i = 0; i <balls.length; i++) {
ball = balls[i];
for (var j = i+1; j < balls.length; j++) {
testBall = balls[j];
if (hitTestCircle(ball,testBall)) {
collideBalls(ball,testBall);
}
}
}
}
Ball collisions in depth
So now we get to the most interesting code of this example. We are going to update
the properties of each ball so 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 are drawn—not where they are right now. This helps keep the
balls from overlapping in a way that will make them stick together.
Search WWH ::

Custom Search