HTML and CSS Reference
In-Depth Information
function
function drawScreen () {
update ();
testWalls ();
collide ();
render ();
}
Updating positions of objects
The update() function loops through all the balls in the balls array and updates the nextx
and nexty properties with the x and y velocity for each ball. We don't directly update x and
y here, because we want to test collisions against walls and other balls before they occur. We
will use the nextx and nexty properties for this purpose:
function
function update () {
for
for ( var
var i = 0 ; i < balls . length ; i ++ ) {
ball = balls [ i ];
ball . nextx = ( ball . x += ball . velocityx );
ball . nexty = ( ball . y += ball . velocityy );
}
}
Better interaction with the walls
Wediscussedtheinteractionsbetweenballsandwallsinthelastexample,butthereisstillone
issue.Because wemovetheballs bythe x and y location oftheir center,theballs wouldmove
halfwayoffthecanvasbeforeabounceoccurred.Tofixthis,weaddorsubtractthe radius of
the ball object,dependingonwhichwallswearetesting.Fortherightsideandbottomofthe
canvas, we add the radius of the ball when we test the walls. In this way, the ball will appear
to bounce exactly when its edge hits a wall. Similarly, we subtract the radius when we test the
left side and the top of the canvas so that the ball does not move off the side before we make
it bounce off a wall:
function
function testWalls () {
var
var ball ;
var
var testBall ;
for
for ( var
var i = 0 ; i < balls . length ; i ++ ) {
ball = balls [ i ];
iif ( ball . nextx + ball . radius > theCanvas . width ) {
ball . velocityx = ball . velocityx * 1 ;
ball . nextx = theCanvas . width - ball . radius ;
}
Search WWH ::




Custom Search