ElasticCollision


Wikipedia: “An elastic collision is a collision in which the total kinetic energy of the colliding bodies after collision is equal to their total kinetic energy before collision.”

In this case ball collision by manipulating DOM elements with CSS animations. This is a basic game mechanic used in many games like Snooker or Hunderds.

Although this tutorial is written in javascript, you should be able to use the same techniques and concepts in almost any development environment. Based on a flash tutorial Managing ball vs ball collision with Flash by Emanuele Feronato.

 

add the balls

In the first function we call, we add the balls to the scene. Just creating some DIV elements, give them some properties and push them to an array to access them later on. We also start the render if the last element is added. To keep the DIV elements in style we set some CSS properties like “border-radius”.

 

 

move the balls

In this function we loop trough the Array which stores the balls an animate them by changing some CSS properties. First we check if any ball reaches the end of the screen. If so we inverse speed for the x and y direction. Next we get the speed value for the actual ball and apply it to the current position. This function is called in the render tick so it is executed on every frame.

 

 

ball collision

There is a whole lot of math in this function. It gets called every time two balls collide together, ball and ball2. If you want to understand how this works, you could read these articles “The Physics of an Elastic Collision”  also “real-world-physics-problems“.

 

 

render tick

This function is called every frame to animate all the Objects on the screen. The function check first if the distance between any balls is greater than the diameter. If not it collides, calls the ball collision function and passes the two colliding balls over. We also call the moveBall & tick function to keep the animation running.

 

 

conclusion

If your game mechanic bases on elastic collision this is a great way of doing it. Full control over the code, light weight, fast and simple.