box2dandenginephysicsgravity

Andengine how to gravity center


How do I reposition the gravity in AndEngine to the center of the screen?

While I'm in the early stages and haven't included my code snippet yet (as I've just started and added the PhysicsBox2D), I'm curious about the underlying logic for achieving this effect. Thank you for taking the time to read, and I appreciate any assistance you can provide.


Solution

  • In box2d there is no option to set the gravity to some direct point, you can just assing as gravity some vector so the gravity itself is rather about some direction.

    Although you can simulate this by

    • setting world gravity to (0,0)

      World world = new World(new Vector2(0,0), true);
      
    • applying a force to body (or all bodies by iterating over them) in every render (game main loop iteration) equal to Gravitation. The example of setting gravity center to some centerBody:

      Body body, centerBody;
      
      ...
      
      //in render method
      float G = 1; //modifier of gravity value - you can make it bigger to have stronger gravity
      
      float distance = body.getPosition().dst( centerBody.getPosition() ); 
      float forceValue = G / (distance * distance);
      
      Vector2 direction = centerBody.getPosition().sub( body.getPosition() ) );
      
      body.applyForce( direction.mul( forceValue ), body.getWorldCenter() ); //the mul method is the same that scl in Libgdx I guess
      

    If you want to apply gravity not to some centerBody but direct point just set new Vector2(0,0) instead of centerBody.getPosition