向精灵节点添加B2Bodies会导致精灵位置发生变化

时间:2013-02-03 13:45:10

标签: iphone cocos2d-iphone box2d

我有一个精灵的蜘蛛侠被添加到场景中。这些精灵的位置是从阵营的位置偏离的,所以我可以围绕批处理节点旋转它们。

当我将B2Body附加到这些精灵中的任何一个时,会出现问题,它们在屏幕上的位置会发生变化。

    balloon1 = [CCSprite spriteWithSpriteFrameName:@"1.png"];
    balloon1.position = ccp(30,30);
    balloon1.tag = 10;
    //balloon1.anchorPoint = ccp(1.1,0.7);
    [spriteNode addChild:balloon1];

    b2BodyDef balloonBodyDef;
balloonBodyDef.type = b2_dynamicBody;
balloonBodyDef.position.Set((160 + balloon1.position.y)/PTM_RATIO, (240 -          balloon1.position.x)/PTM_RATIO);
balloonBodyDef.userData = balloon1;
b2Body *balloonBody = world->CreateBody(&balloonBodyDef);

b2PolygonShape balloon;
    balloon.SetAsBox((balloon1.contentSize.width/PTM_RATIO/2),
               (balloon1.contentSize.height/PTM_RATIO/2));


// Create shape definition and add to body
b2FixtureDef laserGunShapeDef;
laserGunShapeDef.shape = &laser;
//laserGunShapeDef.density = 0.0f;
//laserGunShapeDef.friction = 10.0f;
//laserGunShapeDef.restitution = 0.0f;

b2Fixture *balloonFixture = balloonBody->CreateFixture(&laserGunShapeDef);

如果我将气球作为精灵从文件添加,这可以正常工作,但如上所述完成后,气球就会离开屏幕。

任何想法都会受到赞赏。

2 个答案:

答案 0 :(得分:0)

更改

balloonBodyDef.position.Set((160 + balloon1.position.y)/PTM_RATIO, (240 -          balloon1.position.x)/PTM_RATIO);

balloonBodyDef.position.Set(balloon1.position.x/PTM_RATIO, balloon1.position.y/PTM_RATIO);

还以tick方法处理位置更新。

balloon1.position = ccp(balloonBody->GetPosition().x * PTM_RATIO,
                            (balloonBody->GetPosition().y) * PTM_RATIO);

答案 1 :(得分:0)

我只是猜测,但可能是因为spriteNode的位置。由于精灵附加到精灵节点,(30,30)相对于精灵节点的位置,而不是实际世界的坐标。

所以,尝试使用

CGPoint worldCoordinate = [spriteNode convertToWorldSpace: balloon1.position];
balloonBodyDef.position.Set(worldCoordinate.x/PTM_RATIO, worldCoordinate.y/PTM_RATIO);
和Guru说的一样,不要忘记在tick方法上更新精灵的位置。如果这不起作用,它是一个疯狂的猜测,它应该无关紧要......但首先尝试设置身体的位置,然后设置气球的位置。

无论如何希望这有帮助。