2013-06-29 55 views
0

我和我的一个朋友正在试图用cocos2dx制作坦克。 我们走了多远,该坦克是在屏幕上,枪管连接到罐 enter image description here如何用cocos2dx创建坦克

,但现在我们要尝试到旋转桶,但什么也没发生,上联是在该中心,其中桶开始圆顶结束。两个罐和桶是动态的机构和我们使用的是摩擦接头(见代码)

// 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; 
    } 

回答

0

我认为问题是,你的锚位置是不正确的。此设置:

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

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

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

请参见“本地锚”一节在这里:http://www.iforce2d.net/b2dtut/joints-revolute

+0

图中的红色和绿色轴是两个物体的质量中心,我们已经在该圆顶PyshicsEditor和启动的设置锚点桶,这就是为什么我们在(0,0)上设置localAnchorA和localAnchorB,因为我们已经设置了PyshicsEditor的定位点 – Bjorn

+0

好的,我明白了。我看起来好像身体已经睡着,但注意力并不是指向下,因为我期望自然的休息姿势。无论如何...如果将电机转速设置为非零值,该怎么办?零意味着关节将像刹车一样起作用来阻止枪管移动。 – iforce2d

+0

我不认为电机是选项。我们现在尝试使用摩擦接头并使用“旋转手势”来旋转桶。但我们无法获得旋转手势的工作 – Bjorn