Game Development Reference
In-Depth Information
Listing 13-5. createBodyDef (PhysicsActor.m)
-(b2BodyDef)createBodyDef{
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position = [PhysicsViewController convertPointToB2:self.center];
return bodyDef;
}
In Listing 13-5, we declare a new b2BodyDef and then set its type to b2_dynamicBody so this
b2Body created by this b2BodyDef will participate fully in the simulation. We also specify position
by converting the Actor's center to a b2Vec2 using the task convertPointToB2. Again, this is done
because we want a different scale between the Box2D and the coordinates we are using to represent
our Actors in the scene. Lastly, we simply return it.
PhysicsActor really has two jobs. The first job is to provide a b2BodyDef to be used when adding
the Actor to the scene. The second job is to update the properties of the Actor as the location and
rotation of the corresponding b2Body moves about in the simulation. This is done in the step: task,
shown in Listing 13-6.
Listing 13-6. step: (PhysicsActor.m)
-(void)step:(GameController *)controller{
b2Vec2 position = body->GetPosition();
CGPoint center = [PhysicsViewController convertPointToCG:position];
[self setCenter: center];
[self setRotation:body->GetAngle()];
}
In Listing 13-6, we need to change the location and rotation of the Actor based on the state of the
body property. As you can see, this is pretty simple. We just convert the position of the body to
a CGPoint in the GameController's coordinate system using convertPointToGC :; this new center
value is assigned to the Actor. Then, we set the rotation of the Actor to the angle of the body, using
GetAngle . No conversion is required, as the rotation property of Actor and the angle property of body
are both in radians.
Next, let's explore the how we can extend PhysicsActor so it behaves like the asteroids in our
example.
Extending Physics Actor
We have the class PhysicsActor that provides basic support for an Actor that wishes to participate in
the physics simulation. In this section, we will look at the class Asteroid and understand how we can
modify its behavior to do what we want.
Looking back at the PhysicsActor , note that we didn't mention the starting velocities of the bodies
in the simulation. Let's look at how we customize Asteroid so things start out zipping around our
scene. Listing 13-7 shows how we do this.
 
Search WWH ::




Custom Search