How do I set gravity to any body or screen center? I wondering that's logic..
I have two circle body aBody is staticBody, bBody is dynamic and world gravity(0,0)
.
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.
Vector
between the two points. Read here how to do that. Then add aforce
to the body, using thisVector
, multiplied with the forces strenght. You can read how to do this here – Robert P