如果我用第一批代码创建一个精灵和正文,则精灵集中在圆形体的顶部。但是,如果我使用第二批代码创建精灵,则圆形体的底部会附加到精灵的顶部。两批代码使用以下代码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);
似乎没有定位身体上的精灵,但定位的身体和精灵的世界坐标。