cocos2dx有时会忽略setposition()

时间:2016-03-02 02:05:40

标签: c++ ios iphone cocos2d-x

我有一个循环将对象放在屏幕上。但由于某种原因,虽然在printf中打印了正确的坐标,但是某些对象位于点(0,0),就好像他没有设置它的位置一样。

for (int i =0 ; i < 7; i++) {
        float rand = rand_0_1();
        if (rand <= numberOfNewsObjects/numeroTotal) {
            numberOfNewsObjects--;
            auto  *box = BGObstacle::create();
            box->getPhysicsBody()->setCategoryBitmask((int)PhysicsCategory::Obstacle);
            box->getPhysicsBody()->setContactTestBitmask(true);
            box->setPosition(Vec2((i * (42+3))+4 + 21,(8 * (42+3))+4 + 100 + 21));
            printf("x: %f  y: %f",box->getPosition().x , box->getPosition().y);
            mainLayer->addChild(box, 1);
            arrayOfObstacle.pushBack(box);
            printf(" +%d\n ", i);
        }
}

BGObstacleDrawNode

的子类

使用此并解决

 cocos2d::Director::getInstance()->getScheduler()->performFunctionInCocosThread(‌​[=](){   for (int i =0 ; i < 7; i++) {
            float rand = rand_0_1();
            if (rand <= numberOfNewsObjects/numeroTotal) {
                numberOfNewsObjects--;
                auto  *box = BGObstacle::create();
                box->getPhysicsBody()->setCategoryBitmask((int)PhysicsCategory::Obstacle);
                box->getPhysicsBody()->setContactTestBitmask(true);
                box->setPosition(Vec2((i * (42+3))+4 + 21,(8 * (42+3))+4 + 100 + 21));
                printf("x: %f  y: %f",box->getPosition().x , box->getPosition().y);
                mainLayer->addChild(box, 1);
                arrayOfObstacle.pushBack(box);
                printf(" +%d\n ", i);
            }
    }
});

1 个答案:

答案 0 :(得分:0)

你的代码应该没问题。你在这个功能之外改变他们的位置吗? 我会考虑重写BGObstacle::setPosition(float x, float y)

BGObstacle::setPosition(float x, float y){
    assert(Vec2(x, y).length()>0.001f);
    Sprite::setPosition(x, y);
}

游戏将被中断,当任何BGObstacle被移动到(0,0)时,您可以看到调用堆栈。