I haven't written any articles for a long time. Let's get one. This method is used to create fat bird adventure. Box2D is used in fat bird adventure for Physical Simulation and collision detection. Therefore, a b2body is required for each organ. Then, "Fat Bird" was designed according to "Super Mario Brothers", so the agency can be a platform for various motion tracks, round-robin turtles, and jumping turtles. If box2d is used for these movements, you need to write these tracks by yourself. But the Cocos2d-x already provides a lot of actions, and it's convenient to add actions on your own. In turn, it is very convenient to use sprite to set the b2body position of box2d.
Requirement: All authorities should set the body type to b2_kinematicBody. The advantage of this type is that it can have a speed, but it will not be physically simulated, and it can perform Collision Detection with the body of type b2_dynamicBody.
Suppose we use sprPlatform, a platform with repeated moves. The Code is as follows:
sprPlatform->runAction(CCRepeatForever::create(CCSequence::create(CCMoveBy::create(2, ccp(0, 100)), CCMoveBy::create(2, ccp(0, -100)), NULL)));
Then, set the b2body attribute in the update of sprPlatform.
Void update (float delta) {// update position float angle = getRotation (); CCPoint curPos = getPosition (); b2Vec2 shapeCenter (curPos. x/PTM_RATIO, curPos. y/PTM_RATIO); body-> SetTransform (shapeCenter, CC_DEGREES_TO_RADIANS (360-angle); // update speed, this is to keep the organ uniform body-> SetLinearVelocity (b2Vec2 (curPos. x-lastPos.x)/gPlatformMovingFactor, (curPos. y-lastPos.y)/gPlatformMovingFactor); lastPos = curPos ;}
For gPlatformMovingFactor, It is 1.066681 in fat bird. Because b2_kinematicBody only has no quality and speed, it can only calculate the data based on how many pixels the body has moved in a certain period of time. In short, the sprite movement matches the b2body movement. If b2_kinematicBody does not have velocity, b2_dynamicBody cannot be driven by platform.
Note that the anchor point of the b2body is (0.5, 0.5), and the sprite of cocos2dx can be set by yourself, so you need to perform some simple conversions yourself.
In this way, the b2body is driven by sprite.