init
This commit is contained in:
84
src/sprite.c
Normal file
84
src/sprite.c
Normal file
@@ -0,0 +1,84 @@
|
||||
#include "sprite.h"
|
||||
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#include "raylib.h"
|
||||
#include "raymath.h"
|
||||
|
||||
void* xmalloc(size_t size)
|
||||
{
|
||||
void* p = malloc(size);
|
||||
if (!p) abort();
|
||||
return p;
|
||||
}
|
||||
|
||||
Sprite* sprite_new(const char* path,
|
||||
Vector2* pos,
|
||||
Vector2* anchor,
|
||||
Rectangle* source,
|
||||
Color* color)
|
||||
{
|
||||
assert(path && "path must not be empty");
|
||||
|
||||
Sprite* sprite = xmalloc(sizeof(Sprite));
|
||||
if (!sprite) abort();
|
||||
|
||||
sprite->tex = LoadTexture(path);
|
||||
|
||||
sprite->pos = pos != NULL ? *pos : (Vector2){0, 0};
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
void sprite_draw(Sprite* s)
|
||||
{
|
||||
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(s->pos, s->anchor), s->color);
|
||||
}
|
||||
|
||||
void sprite_free(Sprite* s)
|
||||
{
|
||||
if (s->animation) free(s->animation);
|
||||
UnloadTexture(s->tex);
|
||||
free(s);
|
||||
}
|
||||
|
||||
//
|
||||
// Animation System
|
||||
//
|
||||
void animation_update(Animation* a)
|
||||
{
|
||||
float dt = GetFrameTime();
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user