aboutsummaryrefslogtreecommitdiffstats
path: root/src/animation.c
blob: 52210ae1f777e7ade7b983bb3a704f129a1a9c6d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include "animation.h"
#include "game.h"
#include <raylib.h>

AnimationAsset loadAnimationAssetFromFile(const char* fileName)
{
    AnimationAsset animationAsset;
    animationAsset.image = LoadImageAnim(fileName, &animationAsset.frameCount);

    return animationAsset;
}

void freeAnimationAsset(AnimationAsset* animationAsset)
{
    UnloadImage(animationAsset->image);
}

Animation createAnimation(AnimationAsset* asset, double delay)
{
    Animation animation;

    animation.frameCount = asset->frameCount;
    animation.currentFrame = 0;

    animation.asset = asset;
    animation.texture = LoadTextureFromImage(asset->image);

    animation.width = asset->image.width;
    animation.height = asset->image.height;

    animation.delay = delay;
    animation.lastTime = -1.0; // -1.0 for no last time.

    return animation;
}

void closeAnimation(Animation* animation)
{
    UnloadTexture(animation->texture);
}

void setAnimationFrame(Animation* animation, int frame)
{
    animation->currentFrame = frame;
    unsigned int nextFrameDataOffset = animation->width * animation->height * 4 * frame;

    UpdateTexture(animation->texture, ((unsigned char*)animation->asset->image.data) + nextFrameDataOffset);
}

void runAnimation(Animation* animation)
{
    double currentTime = GetTime();

    if (animation->lastTime == -1.0 || currentTime - animation->lastTime >= animation->delay)
    {
        // Count the frames up.
        int newFrame = animation->currentFrame + 1;

        if (newFrame >= animation->frameCount)
        {
            newFrame = 0;
        }

        // Set the frame
        setAnimationFrame(animation, newFrame);

        animation->lastTime =  currentTime;
    }
}

void pauseAnimation(Animation* animation)
{
    animation->lastTime = -1.0;
}