Search code examples
iosbox2dgravityphysics-engine

Box2D Gravity to specific object?


I see everyone saying that you add gravity like so in a Box2D world:

b2Vec2 gravity = b2Vec2(0.0f, -10.0f);
bool doSleep = false;
world = new b2World(gravity, doSleep);

The thing is though, what if I want gravity only on a specific b2Body which contains userData from a CCSprite? AFAIK this will apply gravity to everything in the world which I do not want, so can someone explain to me how I can apply this gravity only to a specific b2Body?

Thanks!

Edit1: Can I just do this line,

_bottomBody->ApplyForce(gravity, _bottomBody->GetPosition());

Instead of the world = new b2World... etc... Wouldn't that work with gravity only on that b2Body?


Solution

  • Just apply a force/impulse to the specific b2Body every frame. It will emulate gravity.

    // a procedure called every frame
    void Application::on_update_world(double t)
    {
      m_body_with_custom_gravity->applyForce(CUSTOM_GRAVITY * m_body_with_custom_gravity->getMass());
    
      m_phys_world->Step(t, VEL_ITERATIONS, POS_ITERATIONS);
    }
    

    A thread with a question closely related to your: How to apply constant force on a Box2D body?