# How can I make an animation using arrays?

I want to take an array of sprites, for example

sf::Sprite animation[3] = { stepLeft, inMiddle, stepRight };


and construct an animation by looping them. Is this possible? How do I go about it?

• You're on the right track with the array of sprites, but the for loop can't be right. The whole loop will complete every frame. (This means you'll always see the last sprite, or you'll see all of them, stacked. Try it.) Instead, you could set the currently displayed sprite to the next one each frame.
– Anko
Jan 6 '14 at 14:01
• Animations are done in sequence over time. Whether it's frame based or time based. Jan 6 '14 at 15:58
• "Is this possible" is generally not a good thing to ask (the answer is yes or no). "How can I do this" is better, so I've edited your question accordingly.
– user1430
Jan 6 '14 at 16:08

Yes, you can perform sprite animation by using an array of sprites. However, you cannot simply loop over them using a for loop for example, as only the last the sprite in the array would be rendered.

To avoid this you can track the current index into the array, and use this to submit the corresponding sprite to the renderer. After each frame you can accumulate the frame times and after a desired length of time increment the current animation index so that the next sprite in the animation is rendered.

E.g.

if( m_accumulatedTime >= m_animFrameTime )
{
// Reset timer
m_accumulatedTime = 0;

// Move to next frame of animation
m_currentAnimIndex++;

// Loop the animation
if( m_currentAnimIndex > m_animClipSize - 1 )
m_currentAnimIndex = 0;

}

• @FaizAhmed No problem, please mark as answer. Thanks. Jan 6 '14 at 17:04
• Sorry can't do it. I'm new and don't have permission to do it! Jan 6 '14 at 19:03