[英]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.