Search code examples
javasimulationgame-physicsgravity2d-games

Programming Gravity


I'm programming a game (JAVA) and i would like to add some gravity in. I tried to find a formula or someting like this and there is so different way to do it. I'm looking for a formula who can simulate a realistique gravity and make some rebound when the object is touching the floor. Sorry for my bad english.


Solution

  • Near Earth's surface, the gravitational acceleration of all falling bodies is constant (ignoring air resistance). The formula xf = x0 + v0*t + (1/2)*g*t^2 will give you the final position xf given the initial position x0, the initial (vertical) velocity v0 and the time t that the object has been falling. g is a constant that technically depends a bit on your elevation and other factors, but is around 9.81 m/s.

    To do rebound, you'll need first to do some collision detection. When you detect a collision, you'll need to compute the vector normal to the surface (easy if your surface is a horizontal plane) and then "reflect" (sort of) your velocity vector through that vector (if the normal vector is pointing directly upwards, i.e., you're bouncing off a flat surface, this amounts to inverting the velocity v). Note that, to make this realistic, you should probably apply some damping after a bounce: in addition to reflecting the velocity vector, you'll also want to scale it down (depending on how it reflected after the bounce, this could involve reductions in either or both components).

    To actually simulate such a scenario, you can use a variety of techniques: either pre-compute a list of points and then run an animation through them, or you could simulate all of this using Euler's method or some other numeric quadrature technique (trapezoid rule, Runge Kutta, etc.).