Currently I am using the Box2D physics engine in a game of mine - and I was wondering if I could create a gravity well of sorts, in which all the bodies are attracted to a single arbitrary point. Is there a certain开发者_Python百科 way to do this, or will i have to apply a custom force of sorts to each body? (I tried making a static superdense body, but Box2D doesn't apply Newton's Law of Universal Gravitation on a body-to-body basis)
Also, is there a way to make an anti-gravity well? Could I make a denser sphere centered around an arbitrary point and use buoyancy to achieve this?
This functionality isn't built into Box2D unfortunately. The easiest thing to do is get the angle and the distance between the gravity well and the rigid body and set the bodies velocity accordingly.
To get the angle:
double dx = rigidBodyX - gravityWellX;
double dy = rigidBodyY - gravityWellY;
double angle = atan2(dy, dx);
// angle is in radians, use atan2(dy, dx) / PI * 180 if
// you need degrees
To get the distance:
double dx = rigidBodyX - gravityWellX;
double dy = rigidBodyY - gravityWellY;
double dist = sqrt(dx * dx + dy * dy);
I whipped up a quick example using flash and a library I wrote called QuickBox2D. It might not be that helpful since the syntax is very different from the C++ Box2D library, but the basic principal is the same. It's also not a perfect example, but it might get you started.
See The Flash Example
精彩评论