More Balls In A Box

From CodeStuff
Jump to: navigation, search

In A Ball In A Box we were shown how to make a single ball bounce around. The ball used four variables cx,cy,dx,dy two for the position and two for the velocity. If we wanted to have many balls bouncing around at once making four new variable names for each ball would make things very difficult to manage. Luckily you can bundle variables up together.

   var ball_1 = {cx:320, cy:240, dx:3, dy:-3};

Makes a single variable called ball_1 with four parts. You can use the parts of ball_1 by using a dot. is the cx part of ball_1.

The program below, works the same way as the one from A Ball In A Box. The only difference is the ball variables have been bundled into the one object,

Bundling the values into a single object does not have much benefit for just one thing. The program is more or less the same except for extra occurrences of "ball_1.". When you want to have more than one of something it can save a lot of space and time. We can make two balls like this

   var ball_1 = {cx:320, cy:240, dx:3, dy:-3};
   var ball_2 = {cx:330, cy:340, dx:-3, dy:-3};

Because ball_1 and ball_2 have the same parts, you can write a single piece of code to handle them both. The program below does this by making the function moveBall(ball) which does all the work required to move a ball. The move() function now calls moveBall() once for each ball making every ball move.

You can even bundle the variables for the box to make multiple balls and multiple boxes.