Game Development Reference
In-Depth Information
How to do it...
We'll start by defining the node object, in a bean pattern. This will be implemented by per-
forming the following steps:
1. We create a new class called WaypointNode that extends AbstractControl .
2. It needs three integers, f , h , and g .
3. We also have to add two Booleans, open and closed , to aid the pathfinder, a list
of other nodes, called connections , it's current position stored in Vector3f
and another node as parent .
Now we can create the pathfinder itself. This will be implemented by performing the fol-
lowing steps. We create a new class called AStarPathfinder.
1. The pathfinder class needs a list of nodes, called openList , which are the nodes
currently considered.
2. It has to know of the startNode and goalNode .
3. The pathfind method is the heart of the class. We can take a look at it in full,
before explaining it, as shown in the following code:
private void pathfind() {
openList.add(startNode);
WaypointNode current;
while(!openList.isEmpty()) {
current = openList.get(0);
for (WaypointNode neighbor :
current.getConnections()) {
if (!neighbor.isClosed()) {
if (!neighbor.isOpen()) {
openList.add(neighbor);
neighbor.setOpen(true);
setParent(current, neighbor);
} else if (current.getG() +
neighbor.getPosition().distance(goalNode.getPosition())
< neighbor.getG()) { // new path is shorter
setParent(current, neighbor);
}
}
Search WWH ::




Custom Search