Hi!
Is there anyway to make an object to not be affect by gravity in box2d? I have read setting density for the object to 0 does this, but it doesn't work for me.
Any other solution?
Thanks in advance,
HexDump.
A fast, easy to use, free, and community supported 2D game engine
Hi!
Is there anyway to make an object to not be affect by gravity in box2d? I have read setting density for the object to 0 does this, but it doesn't work for me.
Any other solution?
Thanks in advance,
HexDump.
Why don't you just set up your own gravity force and apply it to objects in your physics update loop, if some property of the object is true. Or, you can try to negate the gravity force by applying something upward to objects, but I could see this causing some unstable behavior.
This is similar to what I use to apply gravity to all the objects in my world that I want to follow gravity. This chunk of code goes in my 'tick' function:
//apply gravity to custom sprites
b2Body *spriteBody = NULL;
for(b2Body *b = _world->GetBodyList(); b; b=b->GetNext()) {
if (b->GetUserData() != NULL) {
CCSprite *curSprite = (CCSprite *)b->GetUserData();
if (curSprite.tag == 1 || curSprite.tag == 2 || curSprite.tag == 3 || curSprite.tag == 9) { // All bodies which I want to be affected by gravity by sprite tag
spriteBody = b;
if (spriteBody != NULL) {
spriteBody->ApplyForce(spriteBody->GetMass()*_customBodyGravity, spriteBody->GetWorldCenter());
// b2Vec2 _customBodyGravity; is a variable I keep in my header file
}
}
}
}
I set the gravity variable in my init, or onEnter method, like: _customBodyGravity.Set(0.0f, -20.0f); Though you could simply replace the _customBodyGravity variable in the ApplyForce function above directly, with whatever numbers of your choice.
Note: If you simply want to set your Player Body, for example, you can write:
playerBody->ApplyForce(playerBody->GetMass()*_customBodyGravity, playerBody->GetWorldCenter());
This way, everything I don't want to follow gravity doesn't. In my b2World definition, gravity is set to zero.
JTLYK, this can be easily done with setting the body def type to kinematic.
bd.type = b2_kinematicBody;
You must log in to post.