2
votes

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).

I wanna like this image

1
I guess you have to add a force towards the center to every body in every tick, as the force direction depends on the current position.Robert P
@Springrbua You are right but how ? :/İbrahim Kasapoğlu
First calculate the normalized Vector between the two points. Read here how to do that. Then add a force to the body, using this Vector, multiplied with the forces strenght. You can read how to do this hereRobert P

1 Answers

3
votes

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.