Search code examples
javaandroidlibgdxbox2dgame-physics

How would I create Horizontally centered “Gravity” ? - libGDX -


This is a seemingly simple game mechanic that I've been trying to figure out how to do.

To try and explain I will describe a idea (problem):

  • Basically we say there's a vertical line that is centered in the screen.

  • We have a sprite object that changes it's horizontal velocity to dodge missiles, however in doing that the object would just drift away.

  • How can I add a strong gravity force to the horizontal "center line" of my screen so that my sprite will "fall" back into it every time it boosts its velocity outwards?

I could post my source code but it wouldn't be too helpful to solving the question in this particular situation.

I've searched around for days trying to figure this out so any help especially with code examples would be very helpful!

enter image description here


Solution

  • I've programmed this type of thing in the past. Gravity (in physics) is an acceleration, so

    1) if the sprite is to the right of the line you subtract from its horizontal velocity every 1/n seconds, and

    2) if the sprite is to the left of the line you add to its horizontal velocity every 1/n seconds.

    Experiment with adding/subtracting a constant, or with adding/subtracting a number that increases the farther the sprite is from the center line.

    Either way you do it, that's going to create a pendulum effect. You'll also have to add a dampening factor if you don't want that. One simple approach is that if the sprite is headed away from the center line, the value you add/subtract is larger than if the sprite is heading back towards the center line. So the "gravity" that pulls the sprite to a stop is greater than the gravitational acceleration that brings the sprite back to the center line.