#include #include #include "pacman.h" #include "collision.h" #define PACMAN_SPEED 261 #define PACMAN_SIDE 40 SDL_Rect* get_colliding_tile_raw(SDL_Rect*, struct map* map); SDL_Rect* get_colliding_tile(struct pacman* pacman, struct map* map); void handle_pacman_input(const char* keyboard, struct pacman* pacman, struct map* map) { SDL_Rect r = { .x = pacman->xpos, .y = pacman->ypos, .w = PACMAN_SIDE, .h = PACMAN_SIDE }; if(keyboard[SDL_SCANCODE_UP]) { r.y--; if(get_colliding_tile_raw(&r, map) == NULL) pacman->facing = FACING_UP; } else if(keyboard[SDL_SCANCODE_DOWN]) { r.y++; if(get_colliding_tile_raw(&r, map) == NULL) pacman->facing = FACING_DOWN; } else if(keyboard[SDL_SCANCODE_LEFT]) { r.x--; if(get_colliding_tile_raw(&r, map) == NULL) pacman->facing = FACING_LEFT; } else if(keyboard[SDL_SCANCODE_RIGHT]) { r.x++; if(get_colliding_tile_raw(&r, map) == NULL) pacman->facing = FACING_RIGHT; } } 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; 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; 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) { const struct animation* current_animation = &pacman->animations[pacman->facing]; SDL_Rect d_rect = { .x = pacman->xpos, .y = pacman->ypos, .w = PACMAN_SIDE, .h = PACMAN_SIDE }; 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 }; return get_colliding_tile_raw(&r, map); } SDL_Rect* get_colliding_tile_raw(SDL_Rect* r, struct map* map) { for(int i = 0; i < map->collider_count; i++) { if(is_colliding(r, &map->colliders[i])) { return &map->colliders[i]; } } return NULL; }