diff options
| -rw-r--r-- | dat.h | 7 | ||||
| -rw-r--r-- | physics.c | 20 | ||||
| -rw-r--r-- | sdl3_main.c | 45 |
3 files changed, 38 insertions, 34 deletions
@@ -0,0 +1,7 @@ +typedef struct { + float pos[2]; + float size[2]; + float vel[2]; +} Body; + +int checkcollision(Body *b1, Body *b2); diff --git a/physics.c b/physics.c new file mode 100644 index 0000000..f8d785b --- /dev/null +++ b/physics.c @@ -0,0 +1,20 @@ +#include "dat.h" + +int +checkcollision(Body *a, Body *b) +{ + float p[2], s[2], minx, miny, maxx, maxy; + + for(int i = 0; i < 2; i++) { + s[i] = a->size[i] + b->size[i]; + p[i] = a->pos[i] - b->pos[i]; + } + + minx = p[0] - s[0]; + maxx = p[0] + s[0]; + miny = p[1] - s[1]; + maxy = p[1] + s[1]; + + return minx < 0 && maxx > 0 && miny < 0 && maxy > 0; +} + diff --git a/sdl3_main.c b/sdl3_main.c index b4988bc..b5f1404 100644 --- a/sdl3_main.c +++ b/sdl3_main.c @@ -5,20 +5,11 @@ #include <SDL3/SDL.h> +#include "dat.h" + #define BULLET_SIZE 2 #define ENTITY_SIZE 16 -static void render(void); -static void update(float delta); -static void process_events(void); - -static int checkcollision(float pos1[2], float size1[2], float pos2[2], float size2[2]); - -typedef struct { - float pos[2]; - float vel[2]; -} Body; - typedef struct { Body body; } Player; @@ -34,6 +25,10 @@ typedef struct { bool active; } Bullet; +static void render(void); +static void update(float delta); +static void process_events(void); + static SDL_Window *window; static SDL_Renderer *renderer; static bool running; @@ -68,6 +63,8 @@ main() ghosts[i].active = 1; ghosts[i].body.pos[0] = rand() % 800; ghosts[i].body.pos[1] = rand() % 600; + ghosts[i].body.size[0] = ENTITY_SIZE; + ghosts[i].body.size[1] = ENTITY_SIZE; } running = true; @@ -207,6 +204,8 @@ update(float delta) bullet[i].body.vel[1] = dy * SPEED * 5.0; bullet[i].body.pos[0] = player.body.pos[0]; bullet[i].body.pos[1] = player.body.pos[1]; + bullet[i].body.size[0] = BULLET_SIZE; + bullet[i].body.size[1] = BULLET_SIZE; bullet[i].active = true; } } @@ -219,10 +218,7 @@ update(float delta) if(!ghosts[j].active) continue; - int r = checkcollision( - bullet[i].body.pos, (float[2]){ BULLET_SIZE, BULLET_SIZE }, - ghosts[j].body.pos, (float[2]){ ENTITY_SIZE, ENTITY_SIZE } - ); + int r = checkcollision(&bullet[i].body, &ghosts[j].body); if(r) { ghosts[j].active = false; @@ -313,23 +309,4 @@ process_events() } } -int -checkcollision(float p1[2], float s1[2], float p2[2], float s2[2]) -{ - float p[2], s[2], minx, miny, maxx, maxy; - - - for(int i = 0; i < 2; i++) { - s[i] = s1[i] + s2[i]; - p[i] = p1[i] - p2[i]; - } - - minx = p[0] - s[0]; - maxx = p[0] + s[0]; - miny = p[1] - s[1]; - maxy = p[1] + s[1]; - - return minx < 0 && maxx > 0 && miny < 0 && maxy > 0; -} - |
