2016-03-02 90 views
3

我有一個循環來把對象放在屏幕上。但由於某些原因,儘管在printf中打印了正確的座標,但某些對象仍然處於(0,0)點,就好像他沒有設置位置一樣。cocos2dx有時會忽略設置()

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); 
      } 
    } 
}); 
+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)。

+0

我這樣做和位置總是正確的,但有時對象出現在(0,0),我從不像(0,0)那樣位置。 – Pedro

+1

這實際上是我需要的。如果某些代碼意外地將對象位置更改爲(0,0),則可以立即暫停並查看發生了什麼。 @Pedro – Zen

+0

我使用它,並不存在任何代碼做到這一點。該對象即使如此也出現在(0,0)處。可以是一個cocos2d x錯誤?或者可以在onContactBegin事件中運行? @Zen – Pedro