cocos2d - CCSprite未与b2Body对齐

时间:2013-04-20 02:50:24

标签: iphone cocos2d-iphone box2d ccsprite levelhelper

如果我使用第一批代码创建一个sprite和body,则sprite位于圆形体的顶部。但是如果我用第二批代码创建精灵,圆形体的底部将附加到精灵的顶部。两批代码都使用以下

更新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);

似乎没有将主体定位在精灵上,而是将身体和精灵定位在世界坐标中。

1 个答案:

答案 0 :(得分:0)

我注意到的唯一区别如下。

在第一种情况下,您将英雄初始化为精灵,然后拨打createBody,然后使用self.position,即。{精灵本身的位置。

在第二种情况下,你将一个精灵添加为一个孩子 - createBody现在使用父对象的位置,而不是你要添加的精灵。

相关问题