-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsprite_anim.c
133 lines (70 loc) · 2.29 KB
/
sprite_anim.c
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#include "sprite_anim.h"
sprite_anim_t *load_sprite_anim(const char *path, SDL_Rect src_rect, int num_frames, float frame_delay)
{
sprite_t *new_spr = load_sprite(path);
sprite_anim_t *new_anim = create_sprite_anim(new_spr, src_rect, num_frames, frame_delay);
if (new_anim == NULL)
{
fprintf(stderr, "TODO: ");
if (new_spr != NULL) destroy_sprite(new_spr);
}
return new_anim;
}
sprite_anim_t *create_sprite_anim(sprite_t *spr, SDL_Rect src_rect, int num_frames, float frame_delay)
{
if (spr == NULL || num_frames <= 0 || frame_delay < 0.0f)
{
fprintf(stderr, "");
return NULL;
}
spr->source_rectangle = src_rect;
sprite_anim_t *new_anim = (sprite_anim_t *)malloc(sizeof(sprite_anim_t));
if (new_anim == NULL)
{
fprintf(stderr, "Memory allocation failed for sprite animation.\n");
return NULL;
}
new_anim->animate_horizontal_vertical = true;
new_anim->can_animate = true;
new_anim->spr = spr;
new_anim->num_frames = num_frames;
new_anim->current_frame = 0;
new_anim->frame_delay = frame_delay;
return new_anim;
}
void update_sprite_anim(sprite_anim_t *anim, float delta_time)
{
if (anim == NULL)
{
fprintf(stderr, "");
return;
}
if (anim->can_animate)
{
anim->elapsed_frame_time += delta_time;
if (anim->elapsed_frame_time >= anim->frame_delay)
{
anim->elapsed_frame_time = 0.0;
anim->current_frame = (anim->current_frame + 1) % anim->num_frames;
if (anim->animate_horizontal_vertical)
{
int frame_width = anim->spr->source_rectangle.w;
anim->spr->source_rectangle.x = anim->current_frame * frame_width;
}
else
{
int frame_height = anim->spr->source_rectangle.h;
anim->spr->source_rectangle.y = anim->current_frame * frame_height;
}
}
}
return;
}
void destroy_sprite_anim(sprite_anim_t *anim, bool destroy_spr)
{
if (anim == NULL) return;
if (destroy_spr && anim->spr != NULL) destroy_sprite(anim->spr);
free(anim);
anim = NULL;
return;
}