Programming bouncing ball in JavaScript

While studying Newton's laws of motion during my schooldays, I found some of the questions related to bouncing ball quite fascinating. The sheer number of different kinds of questions that one could come up with just a ball bouncing on the ground is quite a lot.

My attempt is to create the example as simple as possible. I would not be defining additional classes; I would be using the position value which is already present in the DOM Element and adding velocity as a parameter to the DOM Element.

First, let us define the HTML and CSS to get the visual appearance of the ball and the floor right.

<html>
<style>
#ball{
    position: absolute;
    left: 50%;
    top: 0;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background: #005eff;
}
#floor{
    position: absolute;
    bottom: 2px;
    background: #000;
    width: 100%;
    height: 20px;
}
</style>
<body>
    <div id="ball"></div>
    <div id="floor"></div>
</body>
</html>
Now, let the fun begin! Let's start with gravity as a global variable (just in case I feel like adding more balls in the future).

Let us tackle the problem statement at hand in a discrete time way. Let us observe how smooth this is going to be. Adding the following JavaScript to the HTML/CSS shown above.

<script>
// Globals
var gravity = 0.01;
var deltaT = 1; // Updated at every time step
var restitutionCoefficient = 0.8; 
var ball = document.getElementById("ball");
var floor = document.getElementById("floor") 
ball.v = 0; // Initial velocity
setInterval(function(){
    ball.style.top = ball.offsetTop + ball.v * deltaT + 0.5 * gravity * deltaT * deltaT;
    ball.v = ball.v + gravity * deltaT;
    if(ball.offsetTop + ball.offsetHeight > floor.offsetTop){
        ball.v = - ball.v * restitutionCoefficient;
    }
}, deltaT);
</script>

Well, the ball does bounce with this, but it just does not look smooth for some reason. Well, let's try something else.

The issue may be caused by too much computation involved at such a short time step. First of all, the half accelleration times time squared term is insignificant. Let us remove that. After that, divide gravity by a factor of 10 and multiply deltaT by a factor of 10. Observe how things smoothen up.


If you understand this post, it is not very far fetched to think that you can create your own JavaScript game using a few keyboard callbacks. Enjoy!

Comments

Popular posts from this blog

Interactive Monty Hall Problem Implementation

da Vinci of the 21st Century

Image to a string in JavaScript