Creating the world

The first object of Box2D that you will create is the world that holds the simulation itself. In addition to the world, you will also create a few other things in the CreateWorld function from the GameWorld.cpp file:

void GameWorld::CreateWorld()
{
  // create world
  b2Vec2 gravity;
  gravity.Set(0, -10.0f);
  world_ = new b2World(gravity);
  // tell world we want to listen for collisions
  world_->SetContactListener(this);

  // create the moving container that will hold all the game elements
  game_object_layer_ = CCNode::create();
  addChild(game_object_layer_, E_LAYER_FOREGROUND);

#ifdef ENABLE_DEBUG_DRAW
  debug_draw_ = new GLESDebugDraw(PTM_RATIO);
  world_->SetDebugDraw(debug_draw_);
  uint32 flags = 0;
  flags += b2Draw::e_shapeBit;
  //   flags += b2Draw::e_jointBit;
  //    flags += b2Draw::e_aabbBit;
  //    flags += b2Draw::e_pairBit;
  //    flags += b2Draw::e_centerOfMassBit;
  debug_draw_->SetFlags(flags);
#endif
}

We begin by creating a variable gravity of type b2Vec2 and set its value. The b2Vec2 object is Box2D's structure to represent a two dimensional vector. It is similar to the CCPoint object that we use in Cocos2d-x. We then create a new object of b2World, passing in the gravity variable. We also inform the world that we want to listen to collision-related events by calling the SetContactListener function and passing in a reference to GameWorld. We will discuss the outcome of this in the Listening for collisions section of this chapter.

The last object we will create is a CCNode object with the name game_object_layer_. We will add all our game elements' sprites to game_object_layer_. This includes the clown, the collectibles, and the power-ups.

Now when our clown rises higher and higher above the ground, we will simply move this game_object_layer_ object so that the clown is always in the center of the screen. Thus, we can create an illusion of a camera that follows the main character.

We then proceed to create a new object of type GLESDebugDraw. You can find this class in the Box2D test bed provided with the Cocos2d-x C++ tests or more specifically at the path cocos2d-x-2.2.5samplesCppTestCppClassesBox2DTestBedGLES-Render.cpp. The GLESDebugDraw class takes care of rendering primitives based on the various objects contained within the world. What this means is that your bodies and joints will be represented on the screen by tiny colored shapes. For example, all dynamic bodies are colored red while all static ones are colored green!

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

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