使用Box2D将UIImage添加到CCSprite

时间:2011-07-28 03:10:11

标签: objective-c cocos2d-iphone box2d

我想将图像添加到CCSprite,然后在我的Box2d世界中使用它。 createBoxAtLocation正确选择contentSize但从未显示图片...我做错了什么?我是否需要向update()函数添加任何内容?

    CCSprite *sprite = [CCSprite spriteWithFile:@"slider_piece.png"];

    [self createBoxAtLocation:loc1 withSize:boxSize forSprite:sprite];


    -(void) createBoxAtLocation:(CGPoint)location withSize:(CGSize)size forSprite:(CCSprite *)_sprite
    {   
        b2BodyDef bodyDef;
        bodyDef.type = b2_dynamicBody;
        bodyDef.position = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO);
        bodyDef.allowSleep = false;
        //bodyDef.userData = _sprite;

        b2Body *body = world->CreateBody(&bodyDef);
        body->SetUserData(_sprite);

        b2FixtureDef fixtureDef;

        b2PolygonShape shape;
        shape.SetAsBox(_sprite.contentSize.width/2/PTM_RATIO, _sprite.contentSize.height/2/PTM_RATIO); 
        fixtureDef.shape = &shape;   

        body->CreateFixture(&fixtureDef);    
    }

修改

在更新功能中,我有这个,但它会在 sprite.position 行上导致EXC_BAD_ACCESS错误

    for(b2Body *b = world->GetBodyList(); b != NULL; b = b->GetNext()) 
   {    
      if (b->GetUserData() != NULL) {
           CCSprite *sprite = (CCSprite *) b->GetUserData();
           sprite.position = ccp(b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO);
           sprite.rotation = CC_RADIANS_TO_DEGREES(b->GetAngle() * -1);
       }       
   }

1 个答案:

答案 0 :(得分:2)

sprite不是addChild'到任何CCNode(CCLayer或CCScene等)?

如果是的话,

CCSprite *sprite = [CCSprite spriteWithFile:@"slider_piece.png"];

sprite可能会在update()中释放,因为sprite是自动释放的对象。

在这种情况下,你必须在CreateBody,

中保留精灵
body->SetUserData([_sprite retain]);

然后在DestroyBody发布它。

[(CCSprite *)body->GetUserData() release];

顺便说一句,我建议你使用CCBox2D。

<强>编辑:

您是否将精灵添加到您的CCScene或子节点?

[self addChild:sprite];

或者身体的位置(loc1)是否在屏幕范围内?