如何将重力设置为任何物体或屏幕中心?我很好奇其背后的逻辑。
我有两个圆形物体:aBody,它是静态物体,bBody,它是动态物体。世界的重力设置为 (0, 0)。
我希望它类似于链接中的图像:
您所要做的就是施加一个力来模拟屏幕中心的重力(让我们想象一下,在中心有一个非常非常重的物体,它将拉动其他物体)。
该方程众所周知且易于实现 - 请在此处阅读相关内容。
有了方程,你只需像这样实现它:
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() );
当然你可以通过修改center Vector2来修改“重心”。