2012-02-03 60 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