cocos2dx 3.x计划错误

时间:2016-05-05 14:53:35

标签: c++ cocos2d-x

当我尝试实现每n秒添加一个节点时,该过程崩溃。

如果我只是运行runBlock(0.0f),则程序正常运行。

这是我的代码

MainLayer.cpp

bool MainLayer::init(){
   if (!Layer::init()){
    return false;
   }
   block_array = new std::vector<block*>();

   Size visibleSize = Director::getInstance()->getVisibleSize();

   auto body = PhysicsBody::createEdgeBox(visibleSize,PHYSICSBODY_MATERIAL_DEFAULT, 3.0); 
   body->setCategoryBitmask(0x0001);
   body->setCollisionBitmask(0x0001);
   body->setContactTestBitmask(0x0000);
   body->getShape(0)->setRestitution(0.0);

   auto edgeNode = Node::create();
   edgeNode->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2));
   edgeNode->setPhysicsBody(body);
   this->addChild(edgeNode);


   auto sp = Sprite::create("CloseNormal.png");
   sp->setTag(PLAYER);
   auto sp_body = PhysicsBody::createCircle(sp->getContentSize().width / 2);
   sp_body->setCategoryBitmask(0x003);
   sp_body->setCollisionBitmask(0x003);
   sp_body->setContactTestBitmask(0x001);
   sp->setPhysicsBody(sp_body);
   sp->setPosition(visibleSize / 2);
   this->addChild(sp);

   initBlock();
   /**
     When run function "runBlock", process crash!!
   */
   schedule(schedule_selector(MainLayer::runBlock), 5.0f, CC_REPEAT_FOREVER, 0.0f);

  //runBlock(0.0f);     if just run it, everything is right
   return true;
}


 void MainLayer::initBlock(){
   block_array->push_back(new block1());          //block is other class, it has no problem
   block_array->push_back(new block2());
   block_array->push_back(new block3());
 }

void MainLayer::runBlock(float dt){
   Size size = Director::getInstance()->getVisibleSize();
   int len = block_array->size();
   block* bl;
   do 
   {
       int rand = floor(CCRANDOM_0_1()*len);
       if (rand == len){
           rand -= 1;
       }

       bl = (*block_array)[rand];
   } while (bl->node->getParent());            //Crash in here!!!!!

   bl->come(Vec2(size.width*1.5, 0));
   this->addChild(bl->node);

}

我使用的是VS2013。错误信息是

Without exception handling in 0x009D5402(in test.exe)  0xC0000005:  Access violation when reading location 0xFEEF0012

我有调试。 &#34; BL-&gt;节点&#34;分配内存。所以我不认为它是NULL指针错误。但是,我不知道导致坠机的原因是什么。

请帮帮我,谢谢!

2 个答案:

答案 0 :(得分:0)

在几帧之后,所有的块都将拥有父级,而while循环将永远不会退出。

我真的不明白你要在这里完成什么,但我可以建议保留两个数组,在initBlocks()中填充第一个,在runBlock()中随机选择一个,处理它,然后移动它到第二个阵列。

这样你就不需要while循环了,如果继续选择你已经处理过的块,这会浪费很多时间。

答案 1 :(得分:0)

这样做:

void MainLayer::runBlock(float dt)
{ 
    Size size = Director::getInstance()->getVisibleSize();

    //waiting_block_array = block_array when you initialize

   if (waiting_block_array)
   {
        int rand = random (0, waiting_block_array.size () - 1);
        addChild (waiting_block_array[rand]);
        waiting_block_array[rand]->come(Vec2(size.width*1.5, 0));
        this->addChild(waiting_block_array[rand]->node);
        waiting_block_array.erase (waiting_block_array.begin () + rand);
    }