HTML and CSS Reference
In-Depth Information
start in the same location, they would be forever intertwined and would spin off into oblivion.
To be honest, it looks pretty cool when that happens, but that's not the result we are looking
to achieve.
In canvasApp() , we set a variable named tempRadius to 5 . We will use this value as the ra-
dius for each ball we create. Next, we create another new variable named placeOK and set it
to false . When this is equal to true , we know we have found a place to put a ball that is not
on top of another ball.
Next,weentera while() loopthatwillcontinuetoiterateaslongas placeOK is false .Then,
we set all the values for our new ball object:
tempRadius = 5 ;
var
var placeOK = false
false ;
while
while ( ! placeOK ) {
tempX = tempRadius * 3 + ( Math . floor ( Math . random () * theCanvas . width ) - tempRadius * 3 );
tempY = tempRadius * 3 + ( Math . floor ( Math . random () * theCanvas . height ) - tempRadius * 3 );
tempSpeed = 4 ;
tempAngle = Math . floor ( Math . random () * 360 );
tempRadians = tempAngle * Math . PI / 180 ;
tempvelocityx = Math . cos ( tempRadians ) * tempSpeed ;
tempvelocityy = Math . sin ( tempRadians ) * tempSpeed ;
Now,weneedtomakeadynamicobjectoutofthevalueswejustcreatedandplacethatobject
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
thisexample,the mass willbethesame—thevalueof tempRadius .Wedothisbecause,inour
2D environment, the relative size of each ball is a very simple way to create a value for mass .
Because 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,wecreate nextX and nextY propertiesthatareequalto x and y .Wewillusetheseval-
ues 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 };
Nowthatwehaveournewdynamicballobjectrepresentedbythe tempBall variable,wewill
test to see whether it can be placed at the tempX and tempY we randomly created for it. We
Search WWH ::




Custom Search