The user can drag across the screen any number of times but we will always use just one platform, ignoring the previously drawn platform. For this, we define the AddPlatform
function in GameWorld.cpp
:
void GameWorld::AddPlatform(CCPoint start, CCPoint end) { // ensure the platform has only one edge shaped fixture if(platform_->GetBody()->GetFixtureList()) return; // create and add a new fixture based on the user input b2EdgeShape platform_shape; platform_shape.Set(b2Vec2(SCREEN_TO_WORLD(start.x), SCREEN_TO_WORLD(start.y)), b2Vec2(SCREEN_TO_WORLD( end.x), SCREEN_TO_WORLD(end.y))); platform_->GetBody()->CreateFixture(&platform_shape, 0); }
The first statement calls the GetFixtureList
function of the b2Body
class, which returns a pointer to the first b2Fixture
object in the array of fixtures the body has applied to it. This if
condition will ensure that the platform body never gets more than one fixture.
Then, we proceed to actually create the fixture by first creating an edge shape with the Box2D coordinates of the start and end points passed to this function. Now, we have a fixture for the platform's body drawn by the user. Since we will be using this single platform object throughout the game, it will have to be added and removed time and again.
We write the removing logic in the RemovePlatform
function in GameWorld.cpp
:
void GameWorld::RemovePlatform() { // remove the existing fixture if(platform_->GetBody()->GetFixtureList()) { platform_->GetBody()->DestroyFixture( platform_->GetBody()->GetFixtureList()); } }
As simple as that looks, we check whether the platform body has any fixtures on it and simply call the DestroyFixture
function, passing in the pointer to the first fixture. That is all the code you will have to write to destroy the fixture's object, as Box2D handles everything else for you. You will find there are similar functions to destroy bodies and joints as well.
18.224.51.145