Simulate a Balloon in Box2D, iPhone or ANDROID

By | April 12, 2012

Sometimes you may want your body to act against the gravity of the world.
One method to do this is described below.
First what you have to do is to make a body in the shape of a circle and give it the image of a balloon as the userdata.

Then in the tick function write this code.
This method of applying the force is called “The antagonist forces method”
By this method we are giving an upward force to only our balloon body irrespective of the gravitational force.
After running the code you will see your body floating in air like a balloon.

for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
        if (b->GetUserData() != NULL) {
               if (b==baloonBody) {
                         b->ApplyForce( b2Vec2(0.0,9.8*b->GetMass()),b->GetWorldCenter()); // here 0.0 is x, 9.8 is y (the gravity)

Note: Try to change the value 9.8 to higher if you have given your world’s gravity as 9.8. It will produce a balloon effect.
Please leave your comments if this post was useful……….

9 thoughts on “Simulate a Balloon in Box2D, iPhone or ANDROID

  1. Dillon

    I am having issues with how to access the userdata property of my b2body in the tick method. Since i’ve declared them in another method. I don’t know how it’s beating me. Please help!

    1. James

      You can do this same thing in that methods also. we can change the tick method to anything, it’s not a built in method. Only thing is it comes in the code by default. call the other method also same way as tick method that’s all. make your b2body global.

      1. Dillon

        I don’t really get what you mean by calling the other method also the same as tick method. I hope you don’t mind giving me an example.

  2. John

    Thanks. How do I get multiple balloons rising. I’ve made a separate createBalloon method which I call in the init method with the position, as below:

    [self createNewRope:ccp(s.width * 0.25,s.height-200)];
    [self createNewRope:ccp(s.width * 0.50,s.height-200)];
    [self createNewRope:ccp(s.width * 0.75,s.height-200)];
    [self scheduleUpdate];

    Only the last call responds to the new gravity and the other two still have the world gravity. How can I solve this.
    Secondly, How can I define my createBalloon and/or update method so I can set the density for each balloon individually.

    1. James

      Give the sprite of each balloon a tag and identify it in the for loop in the post by taking the userdata and the tag and apply the upward force to your balloon objects.


Leave a Reply

Your email address will not be published. Required fields are marked *