On the Bouncing balls program

Up a level : Fractals and Chaos
Previous page : The onset of Chaos. Bouncing balls.
Next page : Bouncing balls, the maths

Chaotic Bounces – the program

One of the main tricks to get everything deterministic is to do all calculations pretending the canvas has a particular size, and then multiply all the values when drawing with a scale factor to match the actual canvas size.

This then looks like this when drawing.

At each collision, the time for the next collision is calculated, or rather the time it will take for the next collision to occur. This time, and what type of collision that will happen is stored for each ball. As the time ticks on it is compared to that time to know if a new bounce has occurred. The bounces could be against the bowl, one of the walls or the ceiling.

I first do the assignment:

This is to not have to write ball[i] repeatedly. I use this trick quite often. I did a timing test on the two variants, and if anything, this way of doing it was about 2% faster on Chrome. In Firefox the difference was about 10% in favour of the method I have used here. Firefox was also about 30% slower than Chrome.

We get the time to the next bounce from ball.tBounce. We get the time at the start of one particular parabolic motion from ball.t0

The position of the collisions with the bowl is done by solving the quartic equation one gets from combining the equation of the bowl with the equation of the ball’s parabolic trajectory.

The button presses are redirected to the keyboard event function. Like this:

It is done using anonymous functions to preserve the value of “this”. The touch events are redirected to the mouse events in a similar faction.

Initially, I had one setInterval loop for the timing and one requestAnimationframe loop for the graphics, but Firefox throttled the setInteval loop so it became way too slow. I instead moved the calculations inside the requequestAnimationFrame-loop, and rescaled the speed depending on the actual frame-time.

The average distance between adjacent balls is calculated every 10th step.

An interesting bug

In very rare occasions the ball bounced away from the canvas when it hit a corner. After some debugging, I found that it happens when the time to the next bounce was less than one step time.  That meant that the calculation of the time for the bounce against a wall or the ceiling became negative…

I fixed this by adding an absolute value calculation, and then in the bounce function, I did a bit of recursion.  That happens in the last few lines of the function.

…and another one

I noticed that the calculation of the frame time became way off if one happened to view another page as the measurements were done.  I added an event handler if the page became out of focus (blur) that reset the variables in the loop.


Up a level : Fractals and Chaos
Previous page : The onset of Chaos. Bouncing balls.
Next page : Bouncing balls, the mathsLast modified: Jan 6, 2024 @ 14:42