《游戏编程入门》源代码子画面销毁bug解决办法

 原来的 代码是

void GameEngine::CleanupSprites()
{
  // Delete and remove the sprites in the sprite vector
  vector<Sprite*>::iterator siSprite;
  for (siSprite = m_vSprites.begin(); siSprite != m_vSprites.end(); siSprite++)
  {
    delete (*siSprite);
    m_vSprites.erase(siSprite);
    siSprite--;
  }
}

这个是清除Sprite 的 代码,注意,这个 本身 没什么错误,但是m_vSprites.erase(siSprite);
执行过后iterator就无效了,VC6,VS2003,DEV C++都能正常编译,但是vs2008下就不行了

 

修改后的代码为

void GameEngine::CleanupSprites()
{
  // Delete and remove the sprites in the sprite vector
  vector<Sprite*>::iterator siSprite;
  for (siSprite = m_vSprites.begin(); siSprite != m_vSprites.end(); siSprite++)
  {
    delete (*siSprite);
  }
  m_vSprites.clear();
}
//=================================================
//或
void GameEngine::CleanupSprites()
{
 // Delete and remove the sprites in the sprite vector
 vector<Sprite*>::iterator siSprite;
 for (siSprite = m_vSprites.begin(); siSprite != m_vSprites.end();)
 {
  delete (*siSprite);
  siSprite = m_vSprites.erase(siSprite);
 }
}

//=====================================================
似乎 VS2008 的要求 更加 严格了~

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/dkink/archive/2008/04/26/2330905.aspx

 

 

经过自己的修改后 文件变成了:

 

void GameEngine::UpdateSprites()
{
  // Expand the capacity of the sprite vector, if necessary
  if (m_vSprites.size() >= (m_vSprites.capacity() / 2))
    m_vSprites.reserve(m_vSprites.capacity() * 2);

  // Update the sprites in the sprite vector
  RECT          rcOldSpritePos;
  SPRITEACTION  saSpriteAction;
  vector<Sprite*>::iterator siSprite;
  for (siSprite = m_vSprites.begin(); siSprite != m_vSprites.end(); )


  {
    // Save the old sprite position in case we need to restore it
    rcOldSpritePos = (*siSprite)->GetPosition();

    // Update the sprite
    saSpriteAction = (*siSprite)->Update();

    // Handle the SA_ADDSPRITE sprite action
    if (saSpriteAction & SA_ADDSPRITE)
      // Allow the sprite to add its sprite
      AddSprite((*siSprite)->AddSprite());

    // Handle the SA_KILL sprite action
    if (saSpriteAction & SA_KILL)
    {
      // Notify the game that the sprite is dying
      SpriteDying(*siSprite);

      // Kill the sprite
      delete (*siSprite);
      siSprite = m_vSprites.erase(siSprite);
      continue;
    }

    // See if the sprite collided with any others
    if (CheckSpriteCollision(*siSprite))
      // Restore the old sprite position
      (*siSprite)->SetPosition(rcOldSpritePos);
 siSprite++;
  }

}

void GameEngine::CleanupSprites()
{
  // Delete and remove the sprites in the sprite vector
  vector<Sprite*>::iterator siSprite;
  for (siSprite = m_vSprites.begin(); siSprite != m_vSprites.end(); siSprite++)


  {
    delete (*siSprite);

  }
  m_vSprites.clear();


}

 

 

此程序这两个函数都涉及到了 vector 类型的 列表删除问题,cleanupsprites()可以按上面的该法进行修改,但是dataupsprite()中,的该法是自创的,用他的方法自己没能实现。

你可能感兴趣的:(游戏,编程,vector,kill,delete,iterator)