0

Me and a friend of mine are trying to make a tank with cocos2dx. we are so far that the tank is on the screen and the barrel is attached to the tank enter image description here

but now we want to try to the rotate the barrel but nothing is happening, the joint is at the center where the barrel start en de dome ends. both the tank and the barrel are dynamic bodies and we are using a friction joint (see code)

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

1 回答 1

0

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

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

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

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

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

于 2013-06-30T04:31:54.413 回答