Creating the walls

The first physics body we create is the body to represent the walls in our game. As you saw in the screenshot, the clown is restricted on both sides by walls. So let's create these walls in the CreateWall function in GameWorld.cpp:

void GameWorld::CreateWall()
{
  // wall will be a static body placed at the origin
  b2BodyDef wall_def;
  wall_def.position.Set(0, 0);
  wall_ = world_->CreateBody(&wall_def);

  // get variables for the wall edges
  float left_wall = SCREEN_TO_WORLD(WALL_WIDTH);
  float right_wall = SCREEN_TO_WORLD(SCREEN_SIZE.width - WALL_WIDTH);
  float top = SCREEN_TO_WORLD(SCREEN_SIZE.height);
  
  // create and add two fixtures using two edge shapes
  b2EdgeShape wall_shape;
  wall_shape.Set(b2Vec2(left_wall, 0), b2Vec2(left_wall, top));
  wall_->CreateFixture(&wall_shape, 0);
  wall_shape.Set(b2Vec2(right_wall, 0), b2Vec2(right_wall, top));
  wall_->CreateFixture(&wall_shape, 0);
}

We start by creating a b2BodyDef class, which basically is the body definition of the body we wish to create. We need this information because we must pass it into the CreateBody function, which will then return a new b2Body object.

At this moment, the body is a shapeless mass and it feels quite awkward. So we define a few variables that basically represent the left and right faces of the wall and its height. We then create two b2EdgeShape objects that will represent the left and right wall, respectively. We call the Set function and pass in the two end points for both the edge shapes. We then ask the wall body to create a fixture with each of these shapes. The second parameter we pass into CreateFixture is the density of the resultant fixture.

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

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