]> git.lizzy.rs Git - nothing.git/blob - src/player.c
5a1adcbb3dcfdf0cb9b86ecc2ea75b9a7f5e6022
[nothing.git] / src / player.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <SDL2/SDL.h>
4
5 #include "./player.h"
6 #include "./platforms.h"
7
8 #define PLAYER_WIDTH 50.0f
9 #define PLAYER_HEIGHT 50.0f
10 #define PLAYER_SPEED 500.0f
11 #define PLAYER_GRAVITY 1500.0f
12
13 struct player_t {
14     float x, y;
15     float dx, dy;
16 };
17
18 struct player_t *create_player(float x, float y)
19 {
20     struct player_t *player = malloc(sizeof(struct player_t));
21
22     if (player == NULL) {
23         return NULL;
24     }
25
26     player->x = x;
27     player->y = y;
28     player->dx = 0.0f;
29     player->dy = 0.0f;
30
31     return player;
32 }
33
34 void destroy_player(struct player_t * player)
35 {
36     free(player);
37 }
38
39 int render_player(const struct player_t * player,
40                   SDL_Renderer *renderer)
41 {
42     if (SDL_SetRenderDrawColor(renderer, 96, 255, 96, 255) < 0) {
43         return -1;
44     }
45
46     SDL_Rect rect;
47     rect.x = roundf(player->x);
48     rect.y = roundf(player->y);
49     rect.w = roundf(PLAYER_WIDTH);
50     rect.h = roundf(PLAYER_HEIGHT);
51
52     if (SDL_RenderFillRect(renderer, &rect) < 0) {
53         return -1;
54     }
55
56     return 0;
57 }
58
59 void update_player(struct player_t * player,
60                    const struct platforms_t *platforms,
61                    int delta_time)
62 {
63     float d = delta_time / 1000.0;
64
65     float dx = player->dx;
66     float dy = player->dy + PLAYER_GRAVITY * d;
67
68     float x = player->x + dx * d;
69     float y = fmod(player->y + dy * d, 600.0f);
70
71     struct rect_t player_object = {
72         .x = x,
73         .y = y,
74         .w = PLAYER_WIDTH,
75         .h = PLAYER_HEIGHT
76     };
77
78     /* TODO(#6): Implement collision for the left/right sides */
79     if (platforms_rect_object_collide(platforms, &player_object)) {
80         dy = -player->dy * 0.75;
81         x = player->x + dx * d;
82         y = fmod(player->y + dy * d, 600.0f);
83     }
84
85     player->dx = dx;
86     player->dy = dy;
87     player->x = x;
88     player->y = y;
89 }
90
91 void player_move_left(struct player_t *player)
92 {
93     player->dx = -PLAYER_SPEED;
94 }
95
96 void player_move_right(struct player_t *player)
97 {
98     player->dx = PLAYER_SPEED;
99 }
100
101 void player_stop(struct player_t *player)
102 {
103     player->dx = 0.0f;
104 }
105
106 void player_jump(struct player_t *player)
107 {
108     player->dy = -500.0f;
109 }