Although the previous section implements a running character, he is only a genie executing a running frame animation. In this section, I want to associate the genie with the physical world, so that this person has the same actual size as the actual Parkour and will collide.
How can an genie be associated with a physical body to give it a rigid body. In cocos2d-x box2d entry this article, I have a brief introduction. It is not enough to set the userData of a body as a genie. The userData of the body is a void pointer used to store user-defined data. If you assign a value in this way, you will find that the genie and the rigid body are moved separately. This userData is used to store the Genie. It is convenient to retrieve the genie during subsequent position iterations and synchronize it with the position of the rigid body. Look at the update function in the cocos2d-x box2d entry, you know that you still need to do the position iteration.
For convenience, I changed the physical genie CCPhysicsSprite that comes with the engine, removed the chipmunk code, and kept the box2d interface. This is a box2d physical genie B2Sprite.
Change the mRunner type of the member variable in the Runner to B2Sprite, and change the function
mRunner = B2Sprite::createWithSpriteFrameName(runner0); mRunnerSize = mRunner->getContentSize();
Then implement the initBody () and initShape () functions.
Void Runner: initBody () {b2BodyDef bodyDef; bodyDef. type = b2_dynamicBody; // The initial speed is 1.5 bodyDef. linearVelocity = b2Vec2 (1.5, 0); bodyDef. position = b2Vec2 (getOffsetPx ()/RATIO, (GROUND_HEIGHT + mRunnerSize. height/2)/RATIO); mBody = mWorld-> CreateBody (& bodyDef); // associate mRunner-> setB2Body (mBody); mRunner-> setPTMRatio (RATIO );} void Runner: initShape () {b2PolygonShape shape; // defines the shape of the runner, a box with parameters of half width and height. setAsBox (mRunnerSize. width/2/RATIO, mRunnerSize. height/2/RATIO); b2FixtureDef fixDef; fixDef. shape = & shape; mBody-> CreateFixture (& fixDef );}
Then, you can see a Sprite with a collision area.