summaryrefslogtreecommitdiff
path: root/Week1-Pacman/src/animation.c
blob: 0747ba1eb9b4e592725dc3eafba0a89e1a28eb9f (plain)
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "animation.h"
#include <SDL2/SDL_image.h>

const SDL_Rect* current_frame(const struct animation* animation) {
  return &animation->frames[animation->current_frame];
}

void init_animation(struct animation* animation,
                    struct animation_init* init) {
  int initial_frame_count = init->initial_frame_count;

  if (initial_frame_count <= 0) {
    fprintf(stderr, "All animations need to have at least 1 frame!\n");
    exit(1);
  }

  animation->texture = IMG_LoadTexture(init->ren, init->spritesheet);

  if(animation->texture == NULL) {
    printf("Failed to load spritesheet %s, error: %s, exitting!\n",
           init->spritesheet, IMG_GetError());
    exit(1);
  }

  animation->num_frames = initial_frame_count;

  int size = initial_frame_count * sizeof(float);

  animation->frame_times = malloc(size);
  memcpy(animation->frame_times, init->initial_frame_times, size);

  size = initial_frame_count * sizeof(SDL_Rect);

  animation->frames = malloc(size);
  memcpy(animation->frames, init->initial_frames, size);

  animation->angle = init->initial_angle;
}

void update_animation(struct animation* animation, float dt) {
  int frame_index = animation->current_frame;
  float current_frame_time = animation->frame_times[frame_index];

  animation->current_time += dt;

  if(animation->current_time >= current_frame_time) {
    animation->current_time = 0;
    animation->current_frame =
      (frame_index + 1) % animation->num_frames;
  }
}

void draw_animation(struct demo* demo,
                    const struct animation* animation,
                    const SDL_Rect* d_rect) {
  const SDL_Rect* s_rect = current_frame(animation);

  demo_rendercopy_ex(demo, animation->texture,
                     s_rect, d_rect,
                     animation->angle,
                     NULL,
                     SDL_FLIP_NONE);
}