Files
colossus_march/src/sprite.c
2026-03-21 19:35:45 +01:00

77 lines
1.9 KiB
C

#include "sprite.h"
#include <assert.h>
#include <stdlib.h>
#include "raylib.h"
#include "raymath.h"
Sprite* sprite_from_texture(Texture2D tex,
Vector2* anchor,
Rectangle* source,
Color* color,
Arena* arena)
{
Sprite* sprite = arena_alloc(arena, sizeof(Sprite), sizeof(Sprite));
if (!sprite) abort();
sprite->tex = tex;
sprite->source =
source != NULL
? *source
: (Rectangle){0, 0, sprite->tex.width, sprite->tex.height};
sprite->anchor = anchor != NULL ? *anchor
: (Vector2){sprite->source.width / 2.0f,
sprite->source.height / 2.0f};
sprite->color = color != NULL ? *color : (Color){26, 164, 98, 255};
sprite->animation = NULL;
return sprite;
}
Sprite* sprite_new(const char* path,
Vector2* anchor,
Rectangle* source,
Color* color,
Arena* arena,
TextureManager* tm)
{
assert(path && "path must not be empty");
Texture2D tex = tm_load_texture(tm, path);
return sprite_from_texture(tex, anchor, source, color, arena);
}
void sprite_draw(Sprite* s, Vector2 pos)
{
Rectangle source = s->source;
// update source rect if sprite has animation
if (s->animation) {
source.x = source.width * (float)s->animation->current_frame;
}
DrawTextureRec(s->tex, source, Vector2Subtract(pos, s->anchor), s->color);
}
//
// Animation System
//
void animation_update(Animation* a, float dt)
{
a->current_time += dt;
if (a->current_time >= 1.0f / a->fps) {
a->current_time = 0;
a->current_frame++;
if (a->current_frame >= a->frame_count) {
a->current_frame = 0;
}
}
}