Controllers

From Box2D Wiki

Controllers are a Box2D 2.1 feature for easily applying simple physical effects to a given group of bodies. Controllers are extensible by inheriting from b2Controller.

Contents

Usage

Controllers are created with the factory pattern

  1. Create a definition object for the given class you want
  2. Fill the definition object with parameters of the controller
  3. Call b2World::CreateController, and store the returned instance of the class
  4. Add bodies to the controller with b2Controller::AddBody
  5. Delete later using b2World::DestroyController, or let it be cleaned up when you free the world.

Example

The following example creates a b2BuoyancyController, and adds one body, previously created.

b2BuoyancyControllerDef def;
 
def.offset = 15;
def.normal.Set(0,1);
def.density = 2;
def.linearDrag = 2;
def.angularDrag = 1;
 
b2BuoyancyController* bc = (b2BuoyancyController*)m_world->CreateController(&def);
 
bc->AddBody(body);

Extending

Controllers are designed for easy extensibility and sharing. To do this, create your own class inheriting from b2Controller, and corresponding definition class from b2ControllerDef. You then need to implement the following boilerplate methods, in the same fashion as the provided controllers:

b2ControllerDef::Create
b2Controller::Destroy

Then implement the following methods to provided the details of your new constructor

<constructor>         Create a new controller given a definition object
b2Controller::Step    Called once per world step, use this to do something to the bodies
b2Controller::Draw    (optional) Called if controller debug drawing is enabled.

You can iterate over all the bodies in the controller by traversing it's linked list as follows:

for(b2ControllerEdge *i=GetBodyList(); i; i = i->nextBody){
    b2Body* body = i->body;
}

For controllers that apply a force, it is likely that the step argument of Step is not necessary. Use the B2_NOT_USED macro in this case, to suppress the compiler warning.

See also

Category:Controllers

TOOLBOX
LANGUAGES