0

每个人:

问题很奇怪。我先粘贴我的代码。

void GameObjectsLayer::updateEnemy(float interval)
{
    UNREFERENCED_PARAMETER(interval);
    Enemy *lpEnemy = new Enemy("enemy1.png", 1, 10, 8);
    lpEnemy->getSprite()->setAnchorPoint(CCPointZero);
        lpEnemy->setPosition(ccp(-30, 400));
    CCMoveTo *lpMoveAction = CCMoveTo::create(350.0f / ENEMY1_MOVE_SPEED, ccp(320, lpEnemy->getPosition().y));
    CCCallFuncND *lpCallback = CCCallFuncND::create(lpEnemy->getSprite(), callfuncND_selector(GameObjectsLayer::removeEnemy), lpEnemy);
    CCSequence *lpSeqActions = CCSequence::create(lpMoveAction, lpCallback, NULL);
    this->addChild(lpEnemy->getSprite(), 10);
    lpEnemy->getSprite()->runAction(lpSeqActions);
    // When I set the breakpoint here, the _vEnemies is valid and the application runs well.
    _vEnemies->push_back(lpEnemy);
}

void GameObjectsLayer::removeEnemy(CCNode *lpSender, void *lpParam)
{
    Enemy *lpEnemy = (Enemy*)lpParam;
    lpEnemy->getSprite()->stopAllActions();
    this->removeChild(lpSender);
    // When access the _vEnemies variable here, the exception occurs at "_vEnemies->begin()"
    // I set a breakpoint here, the address of _vEnemies is invalid, but I set a breakpoint in the previous function, the _vEnemies has a valid address, what happened? I really can't comprehend the behavior. _vEnemies is the member variable of this class.
    std::vector<Enemy*>::iterator iter = _vEnemies->begin();
    while (iter != _vEnemies->end())
    {
        if (lpEnemy == *iter)
        {
            this->removeChild(lpEnemy->getSprite());
            //delete *iter;
            iter = _vEnemies->erase(iter);
            continue;
        }
        ++iter;
    }
    delete lpEnemy;
}

这两个方法在两个 CCSchedule 中使用,在 init() 方法中初始化,代码如下:

bool GameObjectsLayer::init()
{
    bool bRet = false;
    do
    {
        /* not important, omit them */

        this->schedule(schedule_selector(GameObjectsLayer::updateEnemy), 5.0f);
        this->schedule(schedule_selector(GameObjectsLayer::enemyShoot), 1.0f);

        scheduleUpdate();

        bRet = true;
    }
    while (0);

    return bRet;
}

我头疼。我不知道发生了什么。我的cocos2d-x的版本是2.1.5,IDE是VS2012。感谢帮助..

4

1 回答 1

0

好吧,这是一个旧的,但对于任何可能在这里绊倒的人:

问题似乎出在这一行

CCCallFuncND *lpCallback = CCCallFuncND::create(lpEnemy->getSprite(), callfuncND_selector(GameObjectsLayer::removeEnemy), lpEnemy);

此签名(来自docs)是

static CCCallFuncND* create ( CCObject *pSelectorTarget, 
                              SEL_CallFuncND selector,
                              void * d 
                            )   

*pSelectorTarget是调用的对象selector。所以在这个例子中它应该是this而不是lpEnemy->getSprite().

坦率地说,它没有早点崩溃对我来说似乎有点奇怪。

于 2014-03-27T10:57:23.537 回答