From da98b54216cceb8e7722bd6373e58d44f993b6c2 Mon Sep 17 00:00:00 2001 From: Xevion Date: Sun, 10 Sep 2023 14:17:39 -0500 Subject: [PATCH] feat: wall collisions --- src/direction.rs | 9 +++++++++ src/helper.rs | 15 +++++++++++++++ src/pacman.rs | 16 +++++++++++++++- 3 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 src/helper.rs diff --git a/src/direction.rs b/src/direction.rs index 045cecc..1112510 100644 --- a/src/direction.rs +++ b/src/direction.rs @@ -15,4 +15,13 @@ impl Direction { Direction::Up => 270f64, } } + + pub fn offset(&self) -> (i32, i32) { + match self { + Direction::Right => (1, 0), + Direction::Down => (0, 1), + Direction::Left => (-1, 0), + Direction::Up => (0, -1), + } + } } \ No newline at end of file diff --git a/src/helper.rs b/src/helper.rs new file mode 100644 index 0000000..976867b --- /dev/null +++ b/src/helper.rs @@ -0,0 +1,15 @@ +pub fn is_adjacent(a: (u32, u32), b: (u32, u32), diagonal: bool) -> bool { + let (ax, ay) = a; + let (bx, by) = b; + if diagonal { + (ax == bx && (ay == by + 1 || ay == by - 1)) + || (ay == by && (ax == bx + 1 || ax == bx - 1)) + || (ax == bx + 1 && ay == by + 1) + || (ax == bx + 1 && ay == by - 1) + || (ax == bx - 1 && ay == by + 1) + || (ax == bx - 1 && ay == by - 1) + } else { + (ax == bx && (ay == by + 1 || ay == by - 1)) + || (ay == by && (ax == bx + 1 || ax == bx - 1)) + } +} \ No newline at end of file diff --git a/src/pacman.rs b/src/pacman.rs index 879af6d..2cddfc5 100644 --- a/src/pacman.rs +++ b/src/pacman.rs @@ -4,6 +4,7 @@ use sdl2::{ }; use crate::{ + constants::{BOARD, MapTile}, animation::AnimatedTexture, constants::CELL_SIZE, direction::Direction, entity::Entity, modulation::SpeedModulator, }; @@ -13,6 +14,7 @@ pub struct Pacman<'a> { pub position: (i32, i32), pub direction: Direction, pub next_direction: Option, + pub stopped: bool, speed: u32, modulation: SpeedModulator, sprite: AnimatedTexture<'a>, @@ -25,6 +27,7 @@ impl Pacman<'_> { direction: Direction::Right, next_direction: None, speed: 2, + stopped: false, modulation: SpeedModulator::new(0.9333), sprite: AnimatedTexture::new(atlas, 4, 3, 32, 32, Some((-4, -4))), } @@ -33,6 +36,12 @@ impl Pacman<'_> { pub fn render(&mut self, canvas: &mut Canvas) { self.sprite.render(canvas, self.position, self.direction); } + + fn next_cell(&self) -> (i32, i32) { + let (x, y) = self.direction.offset(); + let cell = self.cell_position(); + (cell.0 as i32 + x, cell.1 as i32 + y) + } } impl Entity for Pacman<'_> { @@ -65,7 +74,7 @@ impl Entity for Pacman<'_> { } } - if self.modulation.next() { + if !self.stopped && self.modulation.next() { let speed = self.speed as i32; match self.direction { Direction::Right => { @@ -82,5 +91,10 @@ impl Entity for Pacman<'_> { } } } + + let next = self.next_cell(); + if BOARD[next.1 as usize][next.0 as usize] == MapTile::Wall { + self.stopped = true; + } } }