Search code examples
javaandroidbox2dphysicsjbox2d

Box2D - Falling body not accelerating under gravity


I have created a basic example of a falling ball but I am slightly confused to why the object is not accelerating while falling. It is travelling at constant speed which isn't what I would expect. This is my first day using Box2D I assume I have missed something basic, but can't figure it out.

public PhysicsWorld() {
    // Step 1: Create Physics World Boundaries
    Vec2 gravity = new Vec2(0, 20);
    boolean doSleep = true;
    world = new World(gravity, doSleep);

    // Dynamic Body
    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyType.DYNAMIC;
    bodyDef.position.set(100, 100);
    body = world.createBody(bodyDef);
    MassData md = new MassData();
    md.mass = 5;
    body.setMassData(md);
    PolygonShape dynamicBox = new PolygonShape();
    dynamicBox.setAsBox(1, 1);
    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = dynamicBox;
    fixtureDef.density = 1;
    fixtureDef.friction = 0.3f;
    body.createFixture(fixtureDef);

    velocityIterations = 6;
    positionIterations = 2;

}

public void update() {
    world.step(timeStep, velocityIterations, positionIterations);
    Log.i("body", "x: " + body.getPosition().x + " y: " + body.getPosition().y);
}

Output:

01-22 21:17:20.750: I/body(7698): x: 100.0 y: 102.0
01-22 21:17:20.777: I/body(7698): x: 100.0 y: 104.0
01-22 21:17:20.796: I/body(7698): x: 100.0 y: 106.0
01-22 21:17:20.824: I/body(7698): x: 100.0 y: 108.0
01-22 21:17:20.847: I/body(7698): x: 100.0 y: 110.0

I would expect gravity to be applied each iteration and increase the balls speed in Y.


Solution

  • This is because the velocity is capped by the engine and you are not using proper world coordinates. Think of it as a meter-kilogram-second system. You have a 1 by 1 meter box falling at 2 meters per 1/40th of a second, or 80 meters per second. That's pretty fast.