Last updated: Jun 22, 2022
Recently I have decided to refurbish something old, that I did 4 years ago for a project of mine. Here is how it looked like:
Balls and Tube
The "tube" component is easy. It's just a background image I am using to create an illusion that the balls are flying inside a sphere-like glass object. The interesting part is the code to create the animations and detect the collisions between the balls and the walls. But let's go step by step.
We said the "tube" is a background image I am adding via simple CSS background property. Let's see the balls themselves. For them I had two choices - try to draw circles in canvas and make them look like balls or use simple images. I choice the later option as I wanted to have more realistic view of the balls. So, with the help of a graphic processing program, a friend of mine created for me 75 images, one for each ball.
Having all the assets we need, we are now ready to go deeper and implement some physics with Matter.js.
Implement, test, implement, test
Before going to the animation itself, we need to mention few Matter.js specific things. When creating animations with this library, one needs to define as minimum:
In our example we use further:
Try and Play
In the beginning of this article, I have posted the link to the GitHub repository with the code and the assets in it. If you want to play more, you can easily check it out and try different modifications. You might want to play with the forces you apply, or the size of the balls, etc. There is plenty of room for experimenting when we talk about Physics. And it's always fun, especially when we add animations to the picture.
As it turns out, Matter.js is a great library for doing 2d realistic animations backed up by the laws of Physics. Of course, there are other options one might choose from, but as we said, this is a matter of choice and project needs. I personally would recommend at least giving a try and see for yourself. For someone with Flash experience or similar, Matter.js is definitely easy to start with. And if you are stubborn enough to keep trying different settings, you might achieve incredible results.
🔥 Thanks for reading! 🔥