【问题标题】:cocos2d - CCSprite not aligned with b2Bodycocos2d - CCSprite 未与 b2Body 对齐
【发布时间】:2013-04-20 02:50:23
【问题描述】:

如果我用第一批代码创建了一个精灵和身体,精灵会在圆形身体的顶部居中。但是如果我用第二批代码创建精灵,圆形主体的底部会附加到精灵的顶部。两批代码都使用如下

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

}

第一批代码-

英雄.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];

第二批代码-

英雄.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);

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

【问题讨论】:

    标签: iphone cocos2d-iphone box2d ccsprite levelhelper


    【解决方案1】:

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

    在您的第一种情况下,您将您的英雄初始化为一个精灵并调用createBody,后者又使用self.position,即。精灵本身的位置。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多