在tick方法中销毁并重新创建一个关节

时间:2012-08-29 18:41:36

标签: cocos2d-iphone box2d box2d-iphone

我创建了一个weldJoint并将其销毁(请参阅下面代码中的update方法)。在破坏焊点时,我设置了线速度,使一个物体朝向另一个物体,形成另一个焊点。 weldJoint永远不会被重新创建。我确信这是由于以下几行:

if (weldJoint == NULL) return;

world->DestroyJoint(weldJoint);
weldJoint = NULL;
代码中的

。因为在下一个时间步长它已经是NULL,所以它不会创建weldJoint。起初我在破坏关节后尝试使用break语句,但是我收到指向该行的EXC_BAD_ACCESS错误:

world->DestroyJoint(weldJoint);

如何创建destroy并重新创建weldJoints?

更新方法:

-(void) update: (ccTime) dt
{

int32 velocityIterations = 8;
int32 positionIterations = 1;

// Instruct the world to perform a single step of simulation. It is
// generally best to keep the time step and iterations fixed.
world->Step(dt, velocityIterations, positionIterations);

// using the iterator pos over the set
std::set<BodyPair *>::iterator pos;

for(pos = bodiesForJoints.begin(); pos != bodiesForJoints.end(); ++pos)
{

b2WeldJointDef weldJointDef;

BodyPair *bodyPair = *pos;
b2Body *bodyA = bodyPair->bodyA;
b2Body *bodyB = bodyPair->bodyB;

weldJointDef.Initialize(bodyA, bodyB, bodyA->GetWorldCenter());

weldJointDef.collideConnected = false;
weldJoint = (b2WeldJoint*) world->CreateJoint(&weldJointDef);

// Free the structure we allocated earlier.
free(bodyPair);

// Remove the entry from the set.
bodiesForJoints.erase(pos);
}

for(b2Body *b = world->GetBodyList(); b; b=b->GetNext())    {
if (b->GetUserData() != NULL)
{
    CCSprite *mainSprite = (CCSprite*)b->GetUserData();
    if (mainSprite.tag == 1) {
        mainSprite.position = CGPointMake( b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO);
        CGPoint mainSpritePosition = mainSprite.position;
        if (mainSprite.isMoved) {

                    if (weldJoint == NULL) return; 

                    world->DestroyJoint(weldJoint);
                    weldJoint = NULL;

                    b2Vec2 velocity = b2Vec2(3.5, 2.2);
                    b->SetLinearVelocity(velocity);  


                }
        }
    }
}

}  

0 个答案:

没有答案