简体   繁体   中英

cocos2d - CCSprite not aligned with b2Body

If I create a sprite and body with the first batch of code, the sprite is centered on top of the circular body. But if I create the sprite with the second batch of code, the bottom of the circular body is attached to the top of the sprite. Both batches of code use the following

Update 1 - I changed createBody so that it now takes position as an input. Then I think I send the correct position in each cause, but I still see the top of the sprite connected to the bottom of the body in the second batch of code.

createBody method:

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

}

First batch of code -

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

Second batch of code -

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

The main difference between the two batches of code is that the first uses initWithSpriteFrameName and the second uses spriteWithSpriteFrameName . Does anyone know how to center the sprite on the body using spriteWithSpriteFrameName?

The strange thing is that this line in the createBody method

     bd.position.Set([xPos doubleValue]/PTM_RATIO, [yPos doubleValue]/PTM_RATIO);

doesn't seem to position the body on the sprite, but to position body and sprite in the world coordinates.

The only difference that I notice is as follows.

In your first case you initialize your hero as a sprite and call createBody which in turn uses self.position , ie. the position of the sprite itself.

In your second case, you add a sprite as a child - createBody now uses the position of the parent object and not the sprite that you are adding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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