Search in sources :

Example 1 with AStarNode

use of com.almasb.fxgl.ai.pathfinding.AStarNode in project FXGL by AlmasB.

the class PathfindingSample method initGame.

@Override
protected void initGame() {
    // 2. init grid width x height
    grid = new AStarGrid(20, 15);
    for (int i = 0; i < 15; i++) {
        for (int j = 0; j < 20; j++) {
            final int x = j;
            final int y = i;
            Entity tile = new Entity();
            tile.getPositionComponent().setValue(j * 40, i * 40);
            Rectangle graphics = new Rectangle(38, 38);
            graphics.setFill(Color.WHITE);
            graphics.setStroke(Color.BLACK);
            // add on click listener
            graphics.setOnMouseClicked(e -> {
                // if left click do search, else place a red obstacle
                if (e.getButton() == MouseButton.PRIMARY) {
                    List<AStarNode> nodes = grid.getPath(0, 0, x, y);
                    nodes.forEach(n -> {
                        getGameWorld().getEntitiesAt(new Point2D(n.getX() * 40, n.getY() * 40)).forEach(Entity::removeFromWorld);
                    });
                } else {
                    grid.setNodeState(x, y, NodeState.NOT_WALKABLE);
                    graphics.setFill(Color.RED);
                }
            });
            tile.getViewComponent().setView(graphics);
            getGameWorld().addEntity(tile);
        }
    }
}
Also used : Entity(com.almasb.fxgl.entity.Entity) AStarNode(com.almasb.fxgl.ai.pathfinding.AStarNode) Point2D(javafx.geometry.Point2D) Rectangle(javafx.scene.shape.Rectangle) AStarGrid(com.almasb.fxgl.ai.pathfinding.AStarGrid)

Aggregations

AStarGrid (com.almasb.fxgl.ai.pathfinding.AStarGrid)1 AStarNode (com.almasb.fxgl.ai.pathfinding.AStarNode)1 Entity (com.almasb.fxgl.entity.Entity)1 Point2D (javafx.geometry.Point2D)1 Rectangle (javafx.scene.shape.Rectangle)1