Last day, I have decided to design a code that can simulate the gravity acting on an object. My aim was to implement the basic position, velocity and acceleration into a code. Then calculate how an object bounces from surfaces. You may remember my Spirit Level example. My aim is to design an environment that a pixel-sized object can move and bounce off the edges with respect to real-life physics phenomenons.
First, let’s understand the mechanics of a free falling object. A gravitational acceleration G effects the object at all instances, therefore speed and position of the object should be calculated for every cycle.
When the object hits the ground, it should bounce. The bounce action reverses the object’s velocity vector by the means of object elasticity and in the bouncing action, acceleration becomes 0 again.
So far so good. We have made the calculation for only the Y-Axis. Now, let’s put the X-Axis into play too. There is no acceleration in this axis so that the object will move in more like a parabolic trajectory.
Good, but if there is no acceleration the object will continue to move in that axis with constant velocity. That is not realistic at all. So I’ve added friction. And I decided to remove the Y-Axis acceleration so that the object will move in much like a pool table fashion.
I also decided to put together some code that will randomize object position and velocity.
Position, velocity, acceleration, elasticity, bounce and friction. They are all set. Now the fun begins. Let’s tie together the acceleration data in both axis with IMU data.
Let’s have a look at the code,
watchX Program starts, Sets variable values and runs the calculating and drawing code forever. The wait is set to 0.002 sec. This results in 500 FPS. I don’t think that it runs that fast but it is pretty quick and looks really fluent in person. This wait effects acceleration and other parameters too. You can change and play with it to change the feel of the program.
We have Set_Variables. This function sets gravitational acceleration along X and Y Axis. Object elasticity (1 is super elastic bounce 0 is no bounce) Friction (This is better set between 0.9999 and 0.995) The position and velocity for X and Y are randomized for fun.
Calculate Position function calculates the position of the object for every instance. The relations here are derived from the formulas in the beginning. These formulas are taken from the real life equation and that’s why the movement looks so realistic. If you can mathematicly model and put anything into a program you will be amazed by the results.
Randomize function sets random position and velocity data just for fun in every button press.
This function looks for borders and calculates collisions and bounce. This is also derived from real-life formulas.
Here you can find the scratch code and play with the parameters yourself. Let’s see what you will come up with!