Custom Gravity of a particular object in Box2D

edited July 2014 in Share Your Work

So finally after searching through the documentation of Box2D I found a function to control gravity acted upon each box2d body. I thought I should share it so that any other person may not have any problem finding it. you can control the gravity of an object by calling setGravityScale(float) function on a body. For example:

    BodyDef bd = new BodyDef();
    bd.type = BodyType.DYNAMIC;
    bd.angle = a;
    bd.position.set(box2d.coordPixelsToWorld(x, y));
    Body body = box2d.createBody(bd);
    PolygonShape sd = new PolygonShape();
    float box2dW = box2d.scalarPixelsToWorld(w/2);
    float box2dH = box2d.scalarPixelsToWorld(h/2);
    sd.setAsBox(box2dW, box2dH);
    body.createFixture(sd, 1);
    body.setGravityScale(-1.0);  // for negative gravity

Comments

Sign In or Register to comment.