2013-04-20 72 views
1

如果我用第一批代碼創建一個精靈和正文,則精靈集中在圓形體的頂部。但是,如果我使用第二批代碼創建精靈,則圓形體的底部會附加到精靈的頂部。兩批代碼使用以下代碼cocos2d - CCSprite與b2Body不對齊

更新1 -我更改了createBody,以便它現在將位置作爲輸入。然後我認爲我在每個原因中發送了正確的位置,但在第二批代碼中我仍然看到精靈的頂部連接到主體的底部。

createBody方法:

- (void)createBody : (NSNumber *)xPos yPos:(NSNumber *)yPos { 

float radius = 16.0f; 

b2BodyDef bd; 
bd.type = b2_dynamicBody; 
bd.linearDamping = 0.1f; 
bd.fixedRotation = true; 
bd.position.Set([xPos doubleValue]/PTM_RATIO, [yPos doubleValue]/PTM_RATIO); 

body = _world->CreateBody(&bd); 

b2CircleShape shape; 
shape.m_radius = radius/PTM_RATIO; 

b2FixtureDef fd; 
fd.shape = &shape; 
fd.density = 1.0f; 
fd.restitution = 0.0f; 
fd.friction = 0.2; 

body->CreateFixture(&fd); 

}

首批代碼 -

Hero.mm -

- (id)initWithWorld:(b2World *)world { 
    if ((self = [super initWithSpriteFrameName:@"animal.png"])) { 
     NSNumber *xPos = [NSNumber numberWithDouble:self.position.x]; 
     NSNumber *yPos = [NSNumber numberWithDouble:self.position.y]; 
     [self createBody:xPos yPos:yPos]; 
    } 
} 

HellowWorld.mm

_hero = [[[Hero alloc] initWithWorld:_world] autorelease]; 
    [_terrain.batchNode addChild:_hero]; 

第二批代碼 -

Hero.mm -

CCSprite *sprite = [CCSprite spriteWithSpriteFrameName:@"animal.png"]; 
[self addChild:sprite]; 
NSNumber *xPos = [NSNumber numberWithDouble: sprite.position.x]; 
NSNumber *yPos = [NSNumber numberWithDouble: sprite.position.y]; 
[self createBody:xPos yPos:yPos]; 

的代碼兩批之間的主要區別在於,第一使用initWithSpriteFrameName和第二個使用spriteWithSpriteFrameName。有誰知道如何使用spriteWithSpriteFrameName將精靈居中在身體上嗎?

奇怪的是,這條線在createBody方法

 bd.position.Set([xPos doubleValue]/PTM_RATIO, [yPos doubleValue]/PTM_RATIO); 

似乎沒有定位身體上的精靈,但定位的身體和精靈的世界座標。

回答

0

我注意到的唯一區別如下。

在你的第一個案例中,你將你的英雄初始化爲一個精靈,並且調用createBody,而後者又使用self.position,即。精靈本身的位置。

在第二種情況下,您將小精靈添加爲小孩 - createBody現在使用父對象的位置,而不是您要添加的精靈。