我正在尝试实现A *路径但是得到了错误的结果:
绿色斑点是道路,红色斑点是障碍。
具体来说这部分是错误的:
为什么要进入树然后再按照正确的路径进行操作?我错过了什么?
这是我的实施:
public List<Spot> process(GameBodyObject me, Point target, ArrayList<GameBodyObject> others) throws Exception {
if(grid == null) {
throw new Exception("You have to initialize AStar first.");
}
grid.unsetObstacleForObject(me);
Spot start = grid.getSpotAtPosition(me.getPosition().getX(), me.getPosition().getY());
Spot end = grid.getSpotAtPosition(target.getX(), target.getY());
end = grid.moveSpotSoThatItDoesntCollide(end, me.getRadius());
List<Spot> openSet = new ArrayList<Spot>(grid.getMaxSize());
List<Spot> closedSet = new ArrayList<>();
List<Spot> path = new ArrayList<>();
openSet.add(start);
while(openSet.size() > 0) {
int winner = 0;
for(int i = 1; i < openSet.size(); i++) {
if(openSet.get(i).getF() < openSet.get(winner).getF()) {
winner = i;
}
}
Spot current = openSet.get(winner);
/*int i = 1;
for(Spot s : Arrays.asList(openSet.getArray())) {
if(s != null) {
System.out.println(i + ". " + s.getF());
i++;
}
}*/
if(current.equals(end)) {
// We are done, reconstruct the path...
Spot temp = current;
path.add(temp);
while(temp.getPrevious() != null) {
path.add(temp.getPrevious());
temp = temp.getPrevious();
}
grid.resetObstacles();
return path;
}
openSet.remove(current);
closedSet.add(current);
List<Spot> neighbors = current.getNeighbors();
for(Spot neighbor : neighbors) {
if(!closedSet.contains(neighbor) && !grid.isCollidingWithObstacle(neighbor, me.getRadius())) {
double tempG = current.getG() + 1;
if(openSet.contains(neighbor)) {
if(tempG < neighbor.getG()) {
neighbor.setG(tempG);
}
} else {
neighbor.setG(tempG);
openSet.add(neighbor);
}
neighbor.setH(heuristic(neighbor, end));
neighbor.setF(neighbor.getG() + neighbor.getH());
neighbor.setPrevious(current);
}
}
}
grid.resetObstacles();
return new ArrayList<>();
}
public double heuristic(Spot spot, Spot end) {
double dx = spot.getX() - end.getX();
double dy = spot.getY() - end.getY();
return Math.abs(dx) + Math.abs(dy);
}
答案 0 :(得分:-1)
因此我的heuristics
似乎有问题,我将其更改为:
public double heuristic(Spot spot, Spot end) {
double dx = spot.getAbsoluteX() - end.getAbsoluteX();
double dy = spot.getAbsoluteY() - end.getAbsoluteY();
//return Math.sqrt(dx * dx + dy * dy);
return Math.abs(dx) + Math.abs(dy);
}
现在它运作正常。