From 933f696fe89c42508a06cf1223d55060952fd2f3 Mon Sep 17 00:00:00 2001 From: Matt Low Date: Fri, 27 Dec 2019 16:55:47 +0400 Subject: [PATCH] Add fix for ghosts getting stuck, Fixes #1 --- core/src/com/me/pacman/entity/Ghost.java | 32 ++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/core/src/com/me/pacman/entity/Ghost.java b/core/src/com/me/pacman/entity/Ghost.java index 666bf70..1548291 100644 --- a/core/src/com/me/pacman/entity/Ghost.java +++ b/core/src/com/me/pacman/entity/Ghost.java @@ -102,7 +102,35 @@ public class Ghost extends MovableEntity { return; } - if (getNextDirection() != null) { + Direction nextDirection = getNextDirection(); + + if (!canMove) { + // we're stuck somewhere, let's change directions to a new valid direction + + // check if we already have a nextDirection which will get us unstuck + if (nextDirection != null) { + Vector2 adjacent = nextDirection.getVector().add(pos); + LevelTile adjTile = state.level.getTile(adjacent); + if (adjTile != null && adjTile.isPassable()) { + return; + } + } + + for (Direction dir : GHOST_ORDER) { + if (dir.isOpposite(currDirection) || dir == currDirection) { + // don't just turn around or keep going our current direction (since we'll continue being stuck) + continue; + } + Vector2 adjacent = dir.getVector().add(pos); + LevelTile adjTile = state.level.getTile(adjacent); + if (adjTile != null && adjTile.isPassable()) { + setNextDirection(dir); + return; + } + } + } + + if (nextDirection != null) { return; } @@ -118,8 +146,8 @@ public class Ghost extends MovableEntity { } Vector2 ahead = new Vector2((int) pos.x, (int) pos.y).add(currDirection.getVector()); + float shortest = Float.MAX_VALUE; - Direction nextDirection = null; for (Direction dir : GHOST_ORDER) { if (dir.isOpposite(currDirection)) {