Animation Timing

Hi all. New member here.
I've just started learning c++ w/SDL and looking for the correct way of doing animation. My current game loop is set to 60FPS. And I'm looking for an easy way to fine tune certain animation speeds. What I have right now is:


1
2
3
4
5
6
7
int frametime;
frametime++;
if (frametime > 100) frametime = 0;
if ((frametime >= 0) && (frametime <= 24)) Blit(325, 60, 0, 0, 40, 40, rabbit);
if ((frametime >= 25) && (frametime <= 49)) Blit(325, 60, 40, 0, 40, 40, rabbit);
if ((frametime >= 50) && (frametime <= 74)) Blit(325, 60, 80, 0, 40, 40, rabbit);
if ((frametime >= 75) && (frametime <= 100)) Blit(325, 60, 120, 0, 40, 40, rabbit);


This code works fine, but I was wondering how it is really done.
BTY My Blit funtion is:
Blit(int x, int y, int srcX, int srcY, int srcW, int scrH, SDL_Surface*)

Thanks
You kind of have the right idea.

Usually, though... data is not hardcoded like that. The actual animation itself would be stored in some other container. And possibly even loaded from an external file.

Typically you'd have a struct or class which manages this kind of thing.

For simplicity, here's an example with a struct:

1
2
3
4
5
6
7
8
struct Frame
{
    int srcX;
    int srcX;
    int srcW;
    int srcH;
    int length;  // in frames or milliseconds... whichever is easiest for you.
};


An animation would then consist of several frames:
1
2
3
4
5
6
struct Animation
{
    std::vector<Frame>    frames;
    int    curFrame;
    int    frameTimeRemaining;
};


From here you'd count down the frame time remaining and advance to the next frame in your animation:
1
2
3
4
5
6
7
8
9
10
11
12
// every update:
frameTimeRemaining -= 1;  // or -= the number of ms that have passed if using ms

if(frameTimeRemaining <= 0)  // this frame is done, move to next one
{
    ++curFrame;
    if(curFrame >= frames.size())
        curFrame = 0;

    // stay on this frame for as long as desired
    frameTimeRemaining += frames[curFrame].length;
}


From there... drawing it is just a matter of pulling out the data from the current frame:

1
2
3
4
// to draw
const Frame& f = frames[curFrame];

Blit( dstX, dstY, f.srcX, f.srcY, f.srcW, f.srcH, rabbit );




With this... the animations can be easily stored somewhere else:

1
2
3
4
5
{
    {  0,0,40,40,  25},
    { 40,0,40,40,  25},
    { 80,0,40,40,  25},
    {120,0,40,40,  25}


Or even loaded from an external file.
Thanks for the quick reply. Very helpful and makes a lot of sense. I do see how this works for the most part even though I have yet to learn structs and classes, which is next on my list.

I built a little fighting game in another language a few years ago and did all my animation sequences in functions with something like my original code and it was tedious. And since I'm learning c++, I'd like to learn better habits.

Thanks for your help. Just what I needed.
Topic archived. No new replies allowed.