58 lines
2.0 KiB
Java
58 lines
2.0 KiB
Java
package se.urmo.game;
|
|
|
|
|
|
import java.awt.Point;
|
|
import java.util.Collections;
|
|
import java.util.List;
|
|
|
|
public class CollisionChecker {
|
|
private GameMap map;
|
|
|
|
public CollisionChecker(GameMap map) {
|
|
this.map = map;
|
|
}
|
|
|
|
public Point getValidDestination(Direction direction, Point position, int agent_width, int agent_height) {
|
|
List<Point> list = switch (direction) {
|
|
case RIGHT -> List.of(
|
|
new Point(position.x + agent_width, position.y), // TOPRIGHT
|
|
new Point(position.x + agent_width, position.y + agent_height)); // BOTTOMRIGHT
|
|
case LEFT -> List.of(
|
|
position, // TOPLEFT
|
|
new Point(position.x, position.y + agent_height)); // BOTTOMLEFT
|
|
case UP -> List.of(
|
|
position, // TOPLEFT
|
|
new Point(position.x + agent_width, position.y)); // TOPRIGHT
|
|
case DOWN -> List.of(
|
|
new Point(position.x, position.y + agent_height), // BOTTOMLEFT
|
|
new Point(position.x + agent_width, position.y + agent_height)); // BOTTOMRIGHT
|
|
default -> Collections.EMPTY_LIST;
|
|
};
|
|
|
|
List<Point> list2 = list.stream()
|
|
.map(p -> normalizePosition(direction, p, agent_width, agent_height))
|
|
.toList();
|
|
|
|
if (map.isPassable(list2)) {
|
|
return normalizePosition(direction, position, agent_width, agent_height);
|
|
}
|
|
return null; // Blocked
|
|
}
|
|
|
|
public Point normalizePosition(Direction dir, Point pos, int agent_width, int agent_height) {
|
|
int x = pos.x;
|
|
int y = pos.y;
|
|
int width = map.getWidth();
|
|
int height = map.getHeight();
|
|
|
|
// tunnel
|
|
if (x < GameMap.OFFSET_X) x = width - agent_width - GameMap.OFFSET_X; // right
|
|
if (x >= (width - GameMap.OFFSET_X)) x = GameMap.OFFSET_X; // left
|
|
//
|
|
// if (y < 0) y = height - 1; // optional vertical wrap
|
|
// else if (y >= height) y = 0;
|
|
|
|
return new Point(x, y);
|
|
}
|
|
}
|