Specifying a different gravity for each body
A question that comes up quite often is how to make certain bodies ignore gravity, while other bodies still obey gravity. This is really easy, so now that we know about forces let's try it. Start with the same scene as in the last topic, with three identical bodies.
// Array to keep track of three bodies
let bodyIds = new Array(3);
// Create world
const worldDef = b2DefaultWorldDef();
const worldId = b2CreateWorld(worldDef);
// let's use the Phaser helper function this time...
// create identical bodies in different positions
for (let i = 0; i < 3; i++) {
let box = CreateBoxPolygon({ worldId: worldId, position: new b2Vec2(-10 + i * 10, 20), type: b2BodyType.b2_dynamicBody, size: 1, density: 1 });
bodyIds[i] = box.bodyId;
}
// a static floor to drop things on
let floor = CreateBoxPolygon({ worldId: worldId, position: new b2Vec2(0, 0), type: b2BodyType.b2_staticBody, size: new b2Vec2(15, 1) });
const floorBodyId = floor.bodyId;
Custom gravity.
Since gravity is really just the same as applying a linear force downwards every time step, all we need to do to counteract it is apply the same force upwards. The required force is relative to the mass of the body:
// In the step/update function
// Cancel gravity for body 1 only
const gravity = b2World_GetGravity(worldId);
const mass = b2Body_GetMass(bodyIds[1]);
const force = new b2Vec3(-gravity.x * mass, -gravity.y * mass);
const center = b2Body_GetWorldCenterOfMass(bodyIds[1]);
b2Body_ApplyForceToCenter(bodyIds[1], force, true);
The same technique can be used to apply gravity in any direction you like, if you need to have something walking on walls or the ceiling for example.
Important: This gravity-cancelling force should be applied before the first time step. If you have the ApplyForce call after the world Step call in your main loop, the body will get one time step at normal gravity and it will have a chance to start moving down before the gravity is cancelled.
Note: Box2D v3.0 provides a gravity scale property for each body that can be used to strengthen or weaken the effect of the world's gravity on it. In many cases this might remove the need to manually apply a force every frame:
// Using gravity scale in Box2D
b2Body_SetGravityScale(bodyIds[1], 0); // Cancel gravity (use -1 to reverse gravity, etc)
It will not help if you want your character to walk on walls though!
Credits
This tutorial is adapted from an original piece of work created by Chris Campbell and is used under license.