Page 1 of 1

Sprite animation/timing methods

Posted: Sun Oct 13, 2013 3:08 am
by 0x0000000
Hello world.

I have a question: how does one time and animate a sprite?
Do I use a timer class and check if a certain amount of milliseconds have passed?
Or do I keep a counter(an integer) that increments each iteration until a certain point is reached?

I know how to clip the sprites, I just need to time the clipping correctly.

Any help and ideas will be appreciated :)

Re: Sprite animation/timing methods

Posted: Sun Oct 13, 2013 7:37 am
by K-Bal
I'd prefer the first method. Libraries like SFML have classes for this but I'd probably just use a float variable and increment it by the frametime in every update cycle.

Re: Sprite animation/timing methods

Posted: Sun Oct 13, 2013 10:56 am
by dandymcgee
I calculate a time delta since the last animation frame change and check if it exceeds the desired delta each update. If it does, go to the next animation frame and reset the deltaTime to 0 subtract the expected duration from the actual duration to minimize error (as per K-Bal's suggestion). This results in a smaller margin of error than basing it solely on frame count without the asynchronicity that a timer introduces.

Psuedocode in case wording was unclear:
struct Frame {
    int duration;
    //...
}

class Sprite {
    int frameCount;
    Frame *frames;
    int frame;
    int ticks;
	
    void Update();
    //...
};

void Sprite::Update(int deltaTime)
{
    ticks += deltaTime;
    if(ticks >= frames[frame].duration) //milliseconds
    {
        ticks -= frames[frame].duration;

        //assumes 1-directional looping order (e.g. 1, 2, 3, 1, 2, 3)
        //in my actual code this is wrapped in a switch(frameOrder) where enum FrameOrder { None, Loop, Oscillation, ReverseLoop }
        frame = ++frame % frameCount;
    }
}

Re: Sprite animation/timing methods

Posted: Sun Oct 13, 2013 10:59 am
by K-Bal
I wouldn't set it to 0 but subtract the keyframe time. This way you're introducing less error.

Re: Sprite animation/timing methods

Posted: Sun Oct 13, 2013 11:07 am
by dandymcgee
K-Bal wrote:I wouldn't set it to 0 but subtract the keyframe time. This way you're introducing less error.
Good idea, hadn't thought of that. Edited my pseudocode, can you double-check the logic?