2016-09-10 103 views
-1

我得到'向量下標超出範圍'錯誤。我知道這是由索引問題造成的,其索引大於數組/集合的最大大小。但是,我無法弄清楚它爲什麼會進入這個階段,因爲我只會在整個項目中增加一個值,並且如果它大於數組的大小,我會將其重置爲0。這是關於SDL中動畫的幀。問題中的索引變量是m_currentFrame。SDL向量下標超出範圍

下面是動畫精靈的「過程」的方法,這是在調用整個項目的唯一的地方「m_currentFrame ++」,我做了它Ctrl + F鍵搜索:

void 
AnimatedSprite::Process(float deltaTime) { 
    // If not paused... 
    if (!m_paused){ 
     // Count the time elapsed. 
     m_timeElapsed += deltaTime; 
     // If the time elapsed is greater than the frame speed. 
     if (m_timeElapsed > (float) m_frameSpeed){ 
      // Move to the next frame. 
      m_currentFrame++; 

      // Reset the time elapsed counter. 
      m_timeElapsed = 0.0f; 

      // If the current frame is greater than the number 
      //   of frame in this animation... 
      if (m_currentFrame > frameCoordinates.size()){ 
       // Reset to the first frame. 
       m_currentFrame = 0; 

       // Stop the animation if it is not looping... 
       if (!m_loop) { 
        m_paused = true; 
       } 

      } 

     } 
    } 
} 

這裏該方法(AnimatedSprite :: DRAW()),即引發錯誤:

void 
AnimatedSprite::Draw(BackBuffer& backbuffer) {  
    //   frame width 
    int frameWidth = m_frameWidth; 

    backbuffer.DrawAnimatedSprite(*this, frameCoordinates[m_currentFrame], m_frameWidth, m_frameHeight, this->GetTexture()); 
} 

這裏是確切的錯誤的屏幕截圖:

error

+0

您應該使用一個調試器,並在您逐步執行該程序時遵循'm_currentFrame'的值。你一定會找到有問題的代碼部分。 – user4407569

回答

0
if (m_currentFrame > frameCoordinates.size()){ 
    // Reset to the first frame. 
    m_currentFrame = 0; 

因爲數組的最高索引是其大小減1(從0開始計數),所以您已經需要重置m_currentFrame == frameCoordinates.size()

+0

工作!謝謝!原來我的講師在我們的框架中提出的評論是不正確的,它說:「// W02.4:如果當前幀比此動畫中的幀數大* – ninja