繁体   English   中英

cocos2d-CCSprite与b2Body不对齐

[英]cocos2d - CCSprite not aligned with 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);

}

第一批代码-

英雄-

- (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];

第二批代码-

英雄-

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

似乎不是将物体放置在精灵上,而是将物体和精灵放置在世界坐标中。

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

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

在第二种情况下,将子级添加为子级createBody现在使用父对象的位置,而不是要添加的子级。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM