为什么我的精灵不与b2Body对齐?

时间:2012-02-03 18:13:05

标签: iphone cocoa cocos2d-iphone box2d box2d-iphone

我最近使用Cocos2d和Box2d开始在iPhone上进行游戏编程。所以这是我的问题:

我有一个继承自CCSprite的Player类,在该类中,有这个方法:

-(void) createBox2dObject:(Player *)sender 
             forWorld:(b2World*)world {

b2BodyDef playerBodyDef;
playerBodyDef.type = b2_dynamicBody;
playerBodyDef.position.Set(sender.position.x/PTM_RATIO, sender.position.y/PTM_RATIO);
playerBodyDef.userData = sender;
body = world->CreateBody(&playerBodyDef);

b2PolygonShape dynamicBox;
dynamicBox.SetAsBox(sender.contentSize.width/PTM_RATIO,
                    sender.contentSize.height/PTM_RATIO);
b2FixtureDef polygonShapeDef;
polygonShapeDef.shape = &dynamicBox;
polygonShapeDef.density = 1.0f;
polygonShapeDef.friction = 1.0f;
polygonShapeDef.restitution = 0;
body->CreateFixture(&polygonShapeDef);
}

以下是我称之为:

    self.player = [Player spriteWithSpriteFrameName:@"runningrupol-1.png"];        
    _player.position = ccp(_player.boundingBox.size.width/2 + 32, _player.boundingBox.size.height/2 + 32);
    self.walkAction = [CCRepeatForever actionWithAction:
                       [CCAnimate actionWithAnimation:walkAnim restoreOriginalFrame:NO]];
    [_player runAction:_walkAction];
    [spriteSheet addChild:_player];
    [_player createBox2dObject:_player forWorld:_world];

显然,我正在使用动画的spritesheet。

以下是我更新世界的方式:

- (void)tick:(ccTime) dt {

    _world->Step(dt, 8, 10);

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

}

以下是我在init方法中调用它的方法:

[self schedule:@selector(tick:)];

这就是我所看到的:

enter image description here

请帮忙。如果您需要其他信息,请告诉我。

2 个答案:

答案 0 :(得分:0)

您可以更改精灵的锚点。这是一个很好的教程:

http://www.qcmat.com/understanding-anchorpoint-in-cocos2d/

答案 1 :(得分:0)

SetAsBox()使用半高和半宽(我知道很古怪),所以将参数除以2:

dynamicBox.SetAsBox(sender.contentSize.width/PTM_RATIO/2,
                sender.contentSize.height/PTM_RATIO/2);

当您尝试此操作时,保持锚点不变(默认值,如果您没有明确设置它应该是ccp(0.5,0.5),精灵的中心,你想要那样)。