use of com.almasb.fxgl.pathfinding.astar.AStarPathfinder in project FXGL by AlmasB.
the class PathfindingSample method initGame.
@Override
protected void initGame() {
// 2. init grid width x height
grid = new AStarGrid(GRID_WIDTH, GRID_HEIGHT);
pathfinder = new AStarPathfinder(grid);
grid.forEach(c -> {
var x = c.getX();
var y = c.getY();
Rectangle rect = new Rectangle(CELL_WIDTH - 2, CELL_HEIGHT - 2);
rect.setFill(Color.WHITE);
rect.setStroke(Color.BLACK);
Entity tile = entityBuilder().at(x * CELL_WIDTH, y * CELL_HEIGHT).view(rect).buildAndAttach();
rect.setOnMouseClicked(e -> {
// if left click do search, else place a red obstacle
if (e.getButton() == MouseButton.PRIMARY) {
var cells = pathfinder.findPath(0, 0, x, y);
cells.forEach(cell -> {
getGameWorld().getEntitiesAt(new Point2D(cell.getX() * CELL_WIDTH, cell.getY() * CELL_HEIGHT)).forEach(Entity::removeFromWorld);
});
} else {
grid.get(x, y).setState(CellState.NOT_WALKABLE);
rect.setFill(Color.RED);
}
});
});
var e = entityBuilder().viewWithBBox(new Rectangle(20, 20)).with(new CellMoveComponent(CELL_WIDTH, CELL_HEIGHT, 100)).buildAndAttach();
e.getComponent(CellMoveComponent.class).setPositionToCell(1, 1);
}
use of com.almasb.fxgl.pathfinding.astar.AStarPathfinder in project FXGL by AlmasB.
the class MassUnitsRTSSample method initGame.
@Override
protected void initGame() {
// 2. init grid width x height
grid = new AStarGrid(GRID_WIDTH, GRID_HEIGHT);
pathfinder = new AStarPathfinder(grid);
grid.forEach(c -> {
var x = c.getX();
var y = c.getY();
Rectangle rect = new Rectangle(CELL_WIDTH - 2, CELL_HEIGHT - 2);
rect.setFill(Color.WHITE);
// rect.setStroke(Color.BLACK);
Entity tile = entityBuilder().at(x * CELL_WIDTH, y * CELL_HEIGHT).view(rect).with(new IDComponent("" + x + "," + y, 0)).buildAndAttach();
rect.setOnMouseClicked(event -> {
// if left click do search, else place a red obstacle
if (event.getButton() == MouseButton.PRIMARY) {
var units = getGameWorld().getEntitiesFiltered(e -> e.getPropertyOptional("type").isPresent());
var cells = grid.getWalkableCells().stream().sorted(Comparator.comparingInt(cell -> cell.distance(grid.get(x, y)))).limit(units.size()).collect(Collectors.toList());
Collections.shuffle(cells);
for (int i = 0; i < units.size(); i++) {
var unit = units.get(i);
var cell = cells.get(i);
unit.getComponent(AStarMoveComponent.class).moveToCell(cell);
}
}
});
});
for (int i = 0; i < 485; i++) {
var color = FXGLMath.randomColor().darker().darker();
var e = entityBuilder().viewWithBBox(new Circle(CELL_WIDTH / 4, CELL_WIDTH / 4, CELL_WIDTH / 4, color)).with(new CellMoveComponent(CELL_WIDTH, CELL_HEIGHT, 300)).with(new AStarMoveComponent(grid)).with("type", "unit").buildAndAttach();
}
}
Aggregations