Game Development Reference
In-Depth Information
Listing 13-3. addActor: (PhysicsViewController.m)
-(void)addActor:(Actor *)actor{
if ([actor isKindOfClass:[PhysicsActor class]]){
PhysicsActor* physicsActor = (PhysicsActor*)actor;
b2BodyDef bodyDef = [physicsActor createBodyDef];
b2Body* body = world->CreateBody(&bodyDef);
b2CircleShape circle;
circle.m_p.Set(0.0f, 0.0f);
circle.m_radius = [PhysicsViewController convertDistanceToB2:[actor radius]];
b2FixtureDef fixtureDef;
fixtureDef.shape = &circle;
fixtureDef.density = [physicsActor radius];
fixtureDef.friction = 0.1f;
fixtureDef.restitution = .8;
body->CreateFixture(&fixtureDef);
[physicsActor setBody:body];
}
[super addActor:actor];
}
In Listing 13-3, we see the overridden task addActor: . In this task, we first check to see if the actor
being added is a PhysicsActor . If it is, we need to do a little work to create a Box2D body within our
world object so we can have our Actor participate in the physics simulation. We also need to create
a fixture so the body has size and mass. Let's look at this step by step.
When creating a body in Box2D, we specify the starting values of body in a struct of type
b2BodyDef. This struct specifies all of the properties of a body, as described earlier in this
chapter. Since things like the location of the body are driven by the physicsActor , we ask it for the
b2BodyDef by calling createBodyDef and storing the value in bodyDef . Once we have a bodyDef , we
call the method CreateBody on the object world and store the result in the b2Body variable body.
The task CreateBody both creates the body and adds it to the simulation. Note that we are using
a method on world to create a b2Body instead of instantiating it ourselves. This is done because
Box2D has very particular memory-management requirements, and it is recommended to always use
the factory methods provided.
Continuing with Listing 13-3, we next create a b2CircleShape called circle. We center the circle on
our body by calling Set and passing in 0.0f for both X and Y locations. We also specify the radius
of the circle. Logically, we know we want the circle to be the same radius as our physicsActor , but
Box2D recommends that we don't make one point equal to one unit in Box2D. In this case, we call
a utility method convertDistanceToB2 to create a scaled value suitable for the Box2D coordinate
system. There are four of these handy conversion methods, and we will look at them more closely
in a bit.
 
Search WWH ::




Custom Search