Creating the base

Now that we have walls, let's create our first GameObject class that will represent the base platform. When I say base platform, I mean the trampoline the clown will be trying relentlessly to jump off at the start of the game. We define the CreateBasePlatform function in GameWorld.cpp:

void GameWorld::CreateBasePlatform()
{
  // base platform will be a static body
  b2BodyDef platform_def;
  platform_def.position.Set(SCREEN_TO_WORLD(416), 
    SCREEN_TO_WORLD(172));
  b2Body* base_platform_body = world_->CreateBody(&platform_def);

  // create an edge slightly above the bottom of the screen
  b2EdgeShape base_platform_shape;
  base_platform_shape.Set(b2Vec2(SCREEN_TO_WORLD(-SCREEN_SIZE.width), 
    0.45f), b2Vec2(SCREEN_TO_WORLD(SCREEN_SIZE.width), 0.45f));
  b2FixtureDef base_platform_fixture_def;
  base_platform_fixture_def.shape = &base_platform_shape;
  // give the base platform perfectly elastic collision response
  base_platform_fixture_def.restitution = 1.0f;
  base_platform_body->CreateFixture(&base_platform_fixture_def);

  // create base platform, set physics body & add to batch node
  base_platform_ = GameObject::create(this, "cjtrapm01.png");
  base_platform_->SetBody(base_platform_body);
  base_platform_->SetType(E_GAME_OBJECT_PLATFORM);
  sprite_batch_node_->addChild(base_platform_, E_LAYER_CLOWN - 1);
}

As you can see, a lot of the code is similar to the code used in creating the walls, except for one minor detail. Here, we actually create a b2FixtureDef object instead of using the shape to create the fixture. We do so because we want to set the value for the restitution of the base platform's fixture. We set the restitution to 1.0f because that is what every clown's dream trampoline should be like—perfectly elastic—and also because we want the clown to keep jumping till the user makes the move.

We then proceed to call the create function of GameObject, passing in a reference to GameWorld and specifying the sprite's frame name. This will return an auto-release GameObject. All that's left is to set its physics body and type before finally adding it to the game's batch node.

Note

Box2D copies the data out of body definitions and fixture definitions when you pass them into the CreateBody and CreateFixture functions, respectively. This means you can use the same b2BodyDef to create multiple b2Body objects.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.83.151