R
R
Robotex2015-09-04 18:31:54
Physics
Robotex, 2015-09-04 18:31:54

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

But now gravity does not behave quite adequately. Moreover, if you set the object to LinearVelocity, then it generally begins to ignore the force applied to it. Tell me how to implement the correct Newtonian physics, as in the video. And I also got the feeling that Box2D is slower than my implementation. Maybe there are better engines with collision handling?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question