【问题标题】:Synchronize functions in Cocos2d-x?Cocos2d-x 中的函数同步?
【发布时间】:2016-12-31 01:45:13
【问题描述】:

我用 cocos2d-x-3.13...

我刚刚开始,但我遇到了一些问题:我在一个向量中有许多精灵,我每秒钟将它们移动到每个位置,当我想删除它们时就会出现问题,因为我有使用循环移动它们的函数:

HelloWorldScene.cpp

bool HelloWorld::init() {
   ...
   _enemies.reserve(15);
   for (unsigned i = 0; i < 5; i++) {
       //Here I create the sprites, and I activate the physics in each one :p
       _enemies.push_back(sprite);
   }
   ...
   /*
   This event checks for each collision, what I do is find the sprite 
   in my vector and then delete the sprite with "removeFromParent ()", 
   then delete the sprite from my vector. it's good, no? :v
   */
   auto contactListener = EventListenerPhysicsContact::create();

   contactListener->onContactBegin = [=](PhysicsContact &contact) {
    auto a = contact.getShapeA()->getBody(); //bullet
    auto b = contact.getShapeB()->getBody(); //enemy

    if (a->getCollisionBitmask() == 2 && b->getCollisionBitmask() == 2) {
        a->getNode()->removeFromParent();

        auto f = std::find(_enemies.begin(), _enemies.end(), ((cocos2d::Sprite*)b->getNode()));
        if (f != _enemies.end()) {
            _enemies.at(std::distance(_enemies.begin(), f))->removeFromParent();
            _enemies.erase(f);
        }
    }
    return true;
  };

   this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(contactListener, this);
   ...
   this->schedule(schedule_selector(HelloWorld::moveEnemies), 1.0f);
   ...
}

void HelloWorld::moveEnemies(float f) {
  for (unsigned i = 0; i < _enemies.size(); i++) 
        {
            cocos2d::Vec2 pos = _enemies.at(i)->getPosition(); //This line throws the exception
            _enemies.at(i)->setPosition(pos.x + 5, pos.y);
        }       
}

我有一个事件,当我按下一个键时,创建一个精灵,如果它与一个敌人发生碰撞就消失了,这里一切都很好,非常简单,但是当你把“moveEnemies”功能和调度器一切很复杂。 .. 向其中一个敌人快速射击会引发异常(Visual Studio 2015):

"读取位置 0xDDDDDE35 时访问冲突"

我认为这是因为矢量是同时被事件和“moveEnemies”函数操纵的吗?

有可能解决这个问题吗?还是我做错了什么?我会很感激任何人指导我...

【问题讨论】:

    标签: c++ synchronization cocos2d-x-3.0 2d-games


    【解决方案1】:

    我找到了一个简单的解决方案,有可能有人会为你服务……

    我们只需为每个精灵添加一个调度程序,向量就会过时。

    auto enemy = cocos2d::Sprite::createWithSpriteFrameName("x.png");
    enemy->setPosition(x, y);
    enemy->setScale(0.5, 0.5);
    //bla bla bla...
    enemy->schedule([enemy](float x) {
        //Code
        auto pos = enemy->getPosition();
        enemy->setPosition(pos.x + 10, pos.y);
    }, 2.0f, "tag");
    

    假设删除事件中的精灵会消除调度程序...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-19
      • 2016-08-09
      • 1970-01-01
      相关资源
      最近更新 更多