2016-09-10 107 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