b2body和b2fixture成阵列

时间:2011-09-09 09:03:09

标签: arrays nsmutablearray nsarray box2d

我可以将b2body或b2fixture添加到NSmutableArray或NSArray中吗? 我一直在寻找一些解决方案,其中一个说它应该首先插入NSValue然后将值添加到nsmutable数组。所以我在我的代码中写这个:

// Create ball body 

          b2BodyDef ballBodyDef;   
          ballBodyDef.type = b2_dynamicBody;
          ballBodyDef.position.Set(0/PTM_RATIO, 300/PTM_RATIO);
            ballBodyDef.userData = [ballSpriteArray objectAtIndex:a];

        _ballBody = _world->CreateBody(&ballBodyDef);


        // Create circle shape on ball
        b2CircleShape circle;
        circle.m_radius = 30.0/PTM_RATIO;

        // Create shape definition and add to body
        b2FixtureDef ballShapeDef;
        ballShapeDef.shape = &circle; 
        ballShapeDef.density = 0.5f;  
        ballShapeDef.friction = 0.5f; 
        ballShapeDef.restitution = 0.6f; 
        _ballFixture = _ballBody->CreateFixture(&ballShapeDef);
        fixValue = [NSValue valueWithBytes:&_ballFixture objCType:@encode(struct b2Fixture)];
                   [ballFixtureArray addObject:fixValue];



        //memberi impulse awal terhadap bola
        b2Vec2 force = b2Vec2(5, 10);
        _ballBody->ApplyLinearImpulse(force, ballBodyDef.position);
        bodyValue = [NSValue valueWithBytes:&_ballBody objCType:@encode(struct b2Body)];
        [ballBodyArray addObject:bodyValue];

在nsmutablearray上获取每个b2Fixture和b2body我在CCtouchBegan方法中确实如此:

for(NSValue *val in ballFixtureArray)
{
    b2Fixture *ballFix;
    [val getValue:&ballFix];


    if (ballFix->TestPoint(locationWorld)) {
    //if([ballFixtureArray objectAtIndex:0]->TestPoint(locationWorld)){
        for (NSValue *bodyVal in ballBodyArray){
            b2MouseJointDef md;
            md.bodyA = _groundBody;
            b2Body *ballBody;
            [bodyVal getValue:&ballBody];
            md.bodyB = ballBody;
            md.target = locationWorld;
            md.collideConnected = true;
            md.maxForce = 1000.0f * ballBody->GetMass();
            _mouseJoint = (b2MouseJoint *)_world->CreateJoint(&md);
            ballBody->SetAwake(true);
        }
    }
}

但它不起作用,另一方面,当我触摸屏幕上的每个位置时应用程序崩溃..
有人可以帮我.. ?? thnx之前每次提前..
问候

1 个答案:

答案 0 :(得分:2)

我建议你使用std :: list或std :: vector来存储这个类。但如果确实需要在NSArray中存储这些类,请用NSObject包装它们:

@interface Wrapper : NSObject
{
   b2Body *body;
}
@property (nonatomic, assign) b2Body *body;
@end