我正在尝试用 box2d 在 cocos2d-x 中制作一个坦克。一切正常,但是当我画坦克时,桶在中间,如图所示。
要绘制坦克,我将位置设置为屏幕的中心,在绘制坦克主体后,我想绘制桶,我给它屏幕的中心 + 相同的关节偏移量(关节在右侧位置)。两个锚点,油箱和枪管都在 (0.5, 0.5) 上,因为我使用与接头相同的偏移量,我预计枪管被绘制在正确的位置,但事实并非如此。
我的代码:
// Create sprite and add it to the layer
CCSprite *tank = CCSprite::create();
//tank->initWithFile("Tanks/001/tank.png");
tank->setPosition(pos);
tank->setTag(1);
this->addChild(tank);
// Create ball body
b2BodyDef tankBodyDef;
tankBodyDef.type = b2_dynamicBody;
tankBodyDef.position = toMeters(&pos);
tankBodyDef.userData = tank;
b2Body *tankBody = _world->CreateBody(&tankBodyDef);
// Create shape definition and add body
shapeCache->addFixturesToBody(tankBody, "001/tank");
// Create sprite and add it to the layer
CCSprite *barrel = CCSprite::create();
//barrel->initWithFile("Tanks/001/barrel.png");
barrel->setPosition(CCPointMake(pos.x + 77, pos.y+117));
barrel->setTag(2);
this->addChild(barrel);
// Create barrel body
barrelBodyDef.type = b2_dynamicBody;
barrelBodyDef.userData = barrel;
barrelBodyDef.position = b2Vec2(tankBodyDef.position.x + 2.40625, tankBodyDef.position.y + 3.65625); // = same offset as joint!?!?!
b2Body *barrelBody = _world->CreateBody(&barrelBodyDef);
// Create shape definition and add body
shapeCache->addFixturesToBody(barrelBody, "001/barrel");
// Create a joint
//
b2RevoluteJointDef armJointDef;
//armJointDef.Initialize(tankBody, barrelBody, b2Vec2(400.0f/PTM_RATIO, 450/PTM_RATIO));
armJointDef.bodyA = tankBody;
armJointDef.bodyB = barrelBody;
armJointDef.localAnchorA.Set(2.40625, 3.65625);
armJointDef.localAnchorB.Set(-2.90625, -0.125);
armJointDef.enableMotor = true;
armJointDef.enableLimit = true;
armJointDef.motorSpeed = 10;
armJointDef.referenceAngle = CC_DEGREES_TO_RADIANS(0); // begin graden
armJointDef.lowerAngle = CC_DEGREES_TO_RADIANS(-50); // max graden naar beneden
armJointDef.upperAngle = CC_DEGREES_TO_RADIANS(00); // max graden naar boven
armJointDef.maxMotorTorque = 48;
armJoint = (b2RevoluteJoint*)_world->CreateJoint(&armJointDef);
我希望有人得到答案:)