2012-02-03 43 views
0

我最近开始使用Cocos2d和Box2d在iPhone上进行游戏编程。因此,这里是我的问题:为什么我的精灵不与b2Body对齐?

我得从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

请帮忙。如果您需要更多信息,请告诉我。

回答

0

SetAsBox()采用半高半宽(古怪的我知道),所以除以2的参数:

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

当您尝试此,按原样离开锚点(如果你没有明确地设置它,默认值应该是ccp(0.5,0.5),你的精灵的中心,你想要的)。

0

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

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

+0

做完这些之后,当力量作用于身体时,精灵的移动速度比身体快。 – Sam 2012-02-04 09:55:39

+0

你可以发布你的代码如何根据物理对象更新你的精灵。 – 2012-02-04 14:04:01

+0

我更新了问题。 – Sam 2012-02-04 15:07:19