如何使用 box2d 使重力在 Libgdx 中居中

How to make gravity to center in Libgdx with box2d

如何将重力设置到任何 body 或屏幕中心?我想知道这是逻辑..

我有两个圆圈bodyaBody是staticBody,bBody是dynamic和worldgravity(0,0).

你所要做的就是施加一个模拟重力的力,以屏幕为中心(假设在中心有一个非常非常重的物体会拉动其他物体)。

方程式众所周知且易于实现 - look here to read about it

有了等式,你只需要像这样实现它:

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() );

当然可以通过修改centerVector2来修改“重心”。