Answer the question
In order to leave comments, you need to log in
How to implement competent radial gravity using Box2D?
The situation is this. I implemented a self-written engine with radial gravity in my toy: https://www.youtube.com/watch?v=mIiC-sHPVAM Everything worked fine until I needed to implement collisions. I decided to rewrite everything on Box2D for this purpose.
I wrote this function:
void PhysicsManager::integrate(const qreal &timeStep)
{
_world->Step(timeStep, _velocityIterations, _positionIterations);
for (int i = 0; i < _gameObjects.count(); i++) {
b2Body * body = _gameObjects[i];
GravitySource * object = static_cast<GravitySource*>(body->GetUserData());
if(object) {
b2Vec2 gravityForce(0.0f, 0.0f);
for(int j = 0; j < _gravitySources.count(); j++) {
b2Body * gravityBody = _gravitySources[j];
if(gravityBody == body) {
continue;
}
b2Vec2 direction = gravityBody->GetPosition() - body->GetPosition();
float32 gravityBodyMass = 0;
if(gravityBody->GetType() == b2_staticBody) {
gravityBodyMass = staticBodyMass(gravityBody);
} else {
gravityBodyMass = gravityBody->GetMass();
}
float32 gravityAcceleration = _gravityConst * body->GetMass() * gravityBodyMass / qPow(direction.Length(), 2);
direction *= 1.0f / direction.Length();
direction *= gravityAcceleration;
gravityForce += direction;
}
body->ApplyForceToCenter(gravityForce, true);
object->setPosition(body->GetPosition());
object->setGravitationVector(gravityForce);
object->setVelocityVector(body->GetLinearVelocity());
}
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question