HTML and CSS Reference
In-Depth Information
Figure 5-8. Two balls colliding at different angles with a line of action drawn between them
Making sure the balls don't start on top of each other
We will work from the code we created for Example 5-6 ( CH5EX6.html ). The first big
change to that code is to make sure the balls don't randomly start on top of one another.
If we let them 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
radius 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, we enter a while() loop that will continue to iterate as long as placeOK is false .
Then, we set all the values for our new ball object:
tempRadius = 5;
var placeOK = false;
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;
Search WWH ::

Custom Search