我有一个循环将对象放在屏幕上。但是由于某种原因,某些对象虽然在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);
            }
    }
});

最佳答案

您的代码应该没问题。您是否在此功能之外更改他们的职位?
我会考虑重写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)时您都可以看到调用堆栈。

08-18 03:09