Bouncing Canvas Balls with Gravity and Friction
I went a little crazy with this one. I know it doesn’t look like much, but there’s a lot going on inside that canvas thingy. If you click on the button or on the canvas, a bunch of black circles will bounce around with their own vectors, speeds, elasticity, and with a shared bit of gravity. (Eventually they’ll stop.) If you want to change somethings, just put numbers into the input boxes. If there’s nothing, then default values will be used. If you enter a letter instead of a number, you’ll get an error.
What was I trying to do?
The idea was to play around with some physics and have a go at some form validation, while using all the wonderful fanciness of requestAnimationFrame. I also wanted to use a prototype class instead of just regular objects. It turned out well, but I did catch a bad case of Shiny Object Syndrome before the end.
How much friction should the floor have? How bouncy should these things be? What kind of gravity should I use? It’s pretty easy to get excited and build bunches of things you won’t actually use. It lost a big chunk of free time just watching things bounce. Sad, really.
Input Fields and Type Coercion
For validation, I wound up using the minus-zero trick to kind of force the input into a number. If this checks out, we’re okay. If it blows up and yields
NaN (not a number) then we need to toss out an alert and refuse to bounce.
Finally, I decided to make the canvas itself a button. It might help with mobile devices, just in case the submit button winds up below the fold. (You shouldn’t have to hit the button and then scroll up quickly in order to see the action.)