如何将物理体与瓦片精灵结合起来?

时间:2014-04-15 06:29:47

标签: cocos2d-iphone box2d

我正在使用瓷砖地图和box2d与cocos2D在iOS游戏中,我想相对于物理主体移动瓷砖,即组合一个或多个瓷砖在身体和接触,如果身体移动然后瓷砖精灵也应该动起来。请提出建议。

1 个答案:

答案 0 :(得分:0)

你可以使用CCPhysicsSprite。

以下代码来自Cocos2d v2中的默认Box2D项目。

-(void) addNewSpriteAtPosition:(CGPoint)p
{
    CCLOG(@"Add sprite %0.2f x %02.f",p.x,p.y);
    // Define the dynamic body.
    //Set up a 1m squared box in the physics world
    b2BodyDef bodyDef;
    bodyDef.type = b2_dynamicBody;
    bodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO);
    b2Body *body = world->CreateBody(&bodyDef);

    // Define another box shape for our dynamic body.
    b2PolygonShape dynamicBox;
    dynamicBox.SetAsBox(.5f, .5f);//These are mid points for our 1m box

    // Define the dynamic body fixture.
    b2FixtureDef fixtureDef;
    fixtureDef.shape = &dynamicBox;
    fixtureDef.density = 1.0f;
    fixtureDef.friction = 0.3f;
    body->CreateFixture(&fixtureDef);


    CCNode *parent = [self getChildByTag:kTagParentNode];

    //We have a 64x64 sprite sheet with 4 different 32x32 images.  The following code is
    //just randomly picking one of the images
    int idx = (CCRANDOM_0_1() > .5 ? 0:1);
    int idy = (CCRANDOM_0_1() > .5 ? 0:1);
    CCPhysicsSprite *sprite = [CCPhysicsSprite spriteWithTexture:spriteTexture_ rect:CGRectMake(32 * idx,32 * idy,32,32)];
    [parent addChild:sprite];

    [sprite setPTMRatio:PTM_RATIO];
    [sprite setB2Body:body];
    [sprite setPosition: ccp( p.x, p.y)];

}

注意在创建正文后设置了精灵的位置。如果您反过来这样做,可能会获得异常。 See here.