From 6f7d1bb16ff266f4126a46c6acb132dd9f80cd86 Mon Sep 17 00:00:00 2001 From: BoredGuy Date: Mon, 30 Dec 2024 18:46:31 +0300 Subject: Smoother Movement Tis all --- Week1-Pacman/src/pacman.c | 67 +++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 62 insertions(+), 5 deletions(-) (limited to 'Week1-Pacman/src/pacman.c') diff --git a/Week1-Pacman/src/pacman.c b/Week1-Pacman/src/pacman.c index f3a4769..de9774d 100644 --- a/Week1-Pacman/src/pacman.c +++ b/Week1-Pacman/src/pacman.c @@ -1,10 +1,13 @@ #include #include #include "pacman.h" +#include "collision.h" #define PACMAN_SPEED 261 #define PACMAN_SIDE 40 +SDL_Rect* get_colliding_tile(struct pacman* pacman, struct map* map); + void handle_pacman_input(SDL_Event* e, struct pacman* pacman) { if(e->type == SDL_KEYDOWN) { @@ -25,19 +28,56 @@ void handle_pacman_input(SDL_Event* e, struct pacman* pacman) { } } -void update_pacman(struct pacman* pacman, float dt) { - +void update_pacman(struct pacman* pacman, float dt, struct map* map) { if(pacman->facing == FACING_UP) { pacman->ypos -= PACMAN_SPEED * dt; + + SDL_Rect* colliding_tile = + get_colliding_tile(pacman, map); + + if(colliding_tile != NULL) { + pacman->ypos = + colliding_tile->y + colliding_tile->h; + } else { + update_animation(&pacman->animations[pacman->facing], dt); + } } else if(pacman->facing == FACING_DOWN) { pacman->ypos += PACMAN_SPEED * dt; + + SDL_Rect* colliding_tile = + get_colliding_tile(pacman, map); + + if(colliding_tile != NULL) { + pacman->ypos = + colliding_tile->y - PACMAN_SIDE; + } else { + update_animation(&pacman->animations[pacman->facing], dt); + } } else if(pacman->facing == FACING_LEFT) { pacman->xpos -= PACMAN_SPEED * dt; - } else { + + SDL_Rect* colliding_tile = + get_colliding_tile(pacman, map); + + if(colliding_tile != NULL) { + pacman->xpos = + colliding_tile->x + colliding_tile->w; + } else { + update_animation(&pacman->animations[pacman->facing], dt); + } + } else if(pacman->facing == FACING_RIGHT) { pacman->xpos += PACMAN_SPEED * dt; - } - update_animation(&pacman->animations[pacman->facing], dt); + SDL_Rect* colliding_tile = + get_colliding_tile(pacman, map); + + if(colliding_tile != NULL) { + pacman->xpos = + colliding_tile->x - PACMAN_SIDE; + } else { + update_animation(&pacman->animations[pacman->facing], dt); + } + } } void draw_pacman(struct demo* demo, const struct pacman* pacman) { @@ -53,3 +93,20 @@ void draw_pacman(struct demo* demo, const struct pacman* pacman) { draw_animation(demo, current_animation, &d_rect); } + +SDL_Rect* get_colliding_tile(struct pacman* pacman, struct map* map) { + SDL_Rect r = (SDL_Rect){ + .x = pacman->xpos, + .y = pacman->ypos, + .w = PACMAN_SIDE, + .h = PACMAN_SIDE + }; + + for(int i = 0; i < map->collider_count; i++) { + if(is_colliding(&r, &map->colliders[i])) { + return &map->colliders[i]; + } + } + + return NULL; +} -- cgit v1.2.3