如何用cocos2dx创建一个坦克

时间:2013-06-29 18:34:51

标签: c++ box2d cocos2d-x

我和我的一个朋友正试图用cocos2dx做一辆坦克。 我们到目前为止,坦克在屏幕上并且枪管连接到坦克 enter image description here

但现在我们想尝试旋转枪管,但没有任何事情发生,关节位于枪管开始到圆顶的中心。坦克和枪管都是动态物体,我们使用摩擦接头(见代码)

// Create sprite and add it to the layer
CCSprite *tank = CCSprite::create();
//tank->initWithFile("../Resources/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;

tankBody = _world->CreateBody(&tankBodyDef);

// Create shape definition and add body
shapeCache->addFixturesToBody(tankBody, "001/tank");


pos = CCPointMake(580, 450);

// Create sprite and add it to the layer
CCSprite *barrel = CCSprite::create();
//barrel->initWithFile("Tanks/001/barrel.png");
barrel->setPosition(pos);
barrel->setTag(2);
this->addChild(barrel);

// Create ball body
b2BodyDef barrelBodyDef;
barrelBodyDef.type = b2_dynamicBody;
barrelBodyDef.position = toMeters(&pos);
barrelBodyDef.userData = barrel;

barrelBody = _world->CreateBody(&barrelBodyDef);
    tankBarrelAnchor =  CreateRevoluteJoint(tankBody, barrelBody, -85.f, 180.f, 2000000.f, 0.f, true, false);
    tankBarrelAnchor->localAnchorA = b2Vec2(0, 0);
    tankBarrelAnchor->localAnchorB = b2Vec2(0, 0);
    tankBarrelAnchor->referenceAngle = 0;
    joint = (b2RevoluteJoint*)_world->CreateJoint(tankBarrelAnchor);

b2RevoluteJointDef* Level::CreateRevoluteJoint(b2Body* A, b2Body* B, float lowerAngle, float upperAngle, float maxMotorTorque, float motorSpeed, boolean enableMotor, boolean collideConnect){
        b2RevoluteJointDef *revoluteJointDef = new b2RevoluteJointDef();
        revoluteJointDef->bodyA = A;
        revoluteJointDef->bodyB = B;
        revoluteJointDef->collideConnected = collideConnect;
        revoluteJointDef->lowerAngle = CC_DEGREES_TO_RADIANS(lowerAngle);
        revoluteJointDef->upperAngle = CC_DEGREES_TO_RADIANS(upperAngle);
        revoluteJointDef->enableLimit = true;
        revoluteJointDef->enableMotor = enableMotor;
        revoluteJointDef->maxMotorTorque = maxMotorTorque;
        revoluteJointDef->motorSpeed = CC_DEGREES_TO_RADIANS(motorSpeed); //1 turn per second counter-clockwise
        return revoluteJointDef;
    }

1 个答案:

答案 0 :(得分:0)

我认为问题在于您的锚位置不正确。此设置:

tankBarrelAnchor->localAnchorA = b2Vec2(0, 0);
tankBarrelAnchor->localAnchorB = b2Vec2(0, 0);

...会将锚点放在屏幕截图中可以看到的那两个红色和绿色轴上,它会尝试将这两个点拉到一起。尝试打开调试绘图中的关节显示,这应该更加明显。

您需要从每个身体的角度将锚点作为局部坐标。例如,从罐体的角度来看,旋转点看起来像(1,2),并且从桶体的角度来看,它看起来像(-1,0)。当然,您使用的尺寸可能不同,但方向应该有些相似。

请参阅此处的“本地主播”部分:http://www.iforce2d.net/b2dtut/joints-revolute