androidlibgdxbox2dgravity

How to make gravity to center in Libgdx with box2d


How can I set gravity to any body or the center of the screen? I am curious about the logic behind it.

I have two circle bodies: aBody, which is a static body, and bBody, which is dynamic. The world has gravity set to (0, 0).

I want it to resemble the image in the link: Image Link


Solution

  • All you have to do is to apply a force that will simulate gravity with center of screen (let's imagine that in the center there is very very heavy object that will be pulling other objects).

    The equation is well known and easy to implement - look here to read about it.

    Having equation you just have to implement it like:

    Body body, centerBody;
    Vector2 center = new Vector2(0, 0);
    ...
    
    //in render method
    float G = 1; //modifier of gravity value - you can make it bigger to have stronger gravity
    
    float distance = body.getPosition().dst( center ); 
    float forceValue = G / (distance * distance);
    
    // Vector2 direction = center.sub( body.getPosition() ) );
    // Due to the comment below it seems that it should be rather:
    Vector2 direction = new Vector2(center.x - body.getPosition().x, center.y - body.getPosition().y);
    
    body.applyForce( direction.scl( forceValue ), body.getWorldCenter() );
    

    Of course you can modify the "center of the gravity" with modifying center Vector2.