Jump to content

  • Log In with Google      Sign In   
  • Create Account


A* Bad heuristic (zigzag)


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
12 replies to this topic

#1 GuiTeK   Members   -  Reputation: 140

Like
0Likes
Like

Posted 16 February 2014 - 02:43 PM

Hello,

 

I'm new to AI programming and I need a pathfinding algorithm for my game which uses isometric tile maps (see below the screenshot in attachment). Player can move in the 8 cardinal directions (North, North East, East, etc.).

 

I successfully implemented the A* algorithm, however I think my heuristic is bad:

heuristic_bad.PNG

As you can see, the algorithm doesn't keep a straight diagonal to the goal. It's not natural at all, I can't let the player move this way.

 

I used this heuristic which is described as the best algorithm for grids that allow 8 directions of movement.

Here is how I implemented it in Java:

public final int ORTHOGONAL_COST = 14;
public final int DIAGONAL_COST = 10;

public float getHeuristicCost(final Point2D.Int source, final Point2D.Int target)
{
	int dx = Math.abs(source.x - target.x);
	int dy = Math.abs(source.y - target.y) / 2;
	
	return ORTHOGONAL_COST * (dx + dy) + (DIAGONAL_COST - 2 * ORTHOGONAL_COST) * Math.min(dx, dy);
}

I divided dy by 2 because of the map's style, it gives a path even weirder if I don't divide by 2.

 

I can understand the path isn't straight because this heuristic isn't fit for my map style, but which one should I use then?

 

Thank you.



Sponsor:

#2 ApochPiQ   Moderators   -  Reputation: 15091

Like
1Likes
Like

Posted 16 February 2014 - 02:58 PM

Are you sure the heuristic is what's wrong and not your overall traversal cost computation?

#3 GuiTeK   Members   -  Reputation: 140

Like
0Likes
Like

Posted 16 February 2014 - 03:47 PM

Are you sure the heuristic is what's wrong and not your overall traversal cost computation?

Hmm... what do you mean? I think I didn't implement such a thing blink.png ...

Sorry but I'm new to AI world...



#4 Pink Horror   Members   -  Reputation: 1149

Like
3Likes
Like

Posted 16 February 2014 - 04:34 PM

The diagonal cost is supposed to be greater than the orthogonal cost. Of course your pathfinder will choose to use all diagonals if those are cheaper. They cover more ground.

Also, if you have to throw in a divide by 2 for no apparent reason other than style, you have other problems too. Your pathfinding shouldn't have to be any different than if you draw the map with no skew.

Edited by Pink Horror, 16 February 2014 - 04:36 PM.


#5 pcmaster   Members   -  Reputation: 659

Like
0Likes
Like

Posted 17 February 2014 - 03:10 AM

I'd first try with the simplest implementation of your cost function and that is simple geometric distance between the two points. That is Math.sqrt(dx * dx + dy * dy). Get rid of that /2 in dy, just as the others said. If this doesn't work, then your problem is elsewhere :) Just then, when it works, you might go on with optimising the function to use integers only (for performance).



#6 Álvaro   Crossbones+   -  Reputation: 12940

Like
3Likes
Like

Posted 17 February 2014 - 05:15 AM

As a very general rule, the heuristic is not to blame for bad quality of the results (as long as it's admissible). If your algorithm is picking a result you don't like among many possible results with the same cost, it means your cost function doesn't accurately reflect your preferences.

#7 GuiTeK   Members   -  Reputation: 140

Like
0Likes
Like

Posted 17 February 2014 - 12:16 PM

The diagonal cost is supposed to be greater than the orthogonal cost. Of course your pathfinder will choose to use all diagonals if those are cheaper. They cover more ground.

Also, if you have to throw in a divide by 2 for no apparent reason other than style, you have other problems too. Your pathfinding shouldn't have to be any different than if you draw the map with no skew.

I've taken into account your tips. Here is the code and the results:

public final int ORTHOGONAL_COST = 10;
public final int DIAGONAL_COST = 14;

public float getHeuristicCost(final Point2D.Int source, final Point2D.Int target)
{
	int dx = Math.abs(source.x - target.x);
	int dy = Math.abs(source.y - target.y);
	
	return ORTHOGONAL_COST * (dx + dy) + (DIAGONAL_COST - 2 * ORTHOGONAL_COST) * Math.min(dx, dy);
}

diagonal_distance.PNG

 

Maybe I don't get the expected result (straight diagonal line) because I don't handle the coordinates the right way? Below you can see how I do it:

grid_blank.PNG

Is it right?

 

 

 

I'd first try with the simplest implementation of your cost function and that is simple geometric distance between the two points. That is Math.sqrt(dx * dx + dy * dy). Get rid of that /2 in dy, just as the others said. If this doesn't work, then your problem is elsewhere smile.png Just then, when it works, you might go on with optimising the function to use integers only (for performance).

Tried that too. Code & results:

public float getHeuristicCost(final Point2D.Int source, final Point2D.Int target)
{
	int dx = Math.abs(source.x - target.x);
	int dy = Math.abs(source.y - target.y);
	
	return (float)Math.sqrt(dx * dx + dy * dy);
}

euclidean_distance.PNG

 

 

As a very general rule, the heuristic is not to blame for bad quality of the results (as long as it's admissible). If your algorithm is picking a result you don't like among many possible results with the same cost, it means your cost function doesn't accurately reflect your preferences.

How can I adjust my cost function? I just try again and again until I find something that matches with what I want?



#8 ApochPiQ   Moderators   -  Reputation: 15091

Like
3Likes
Like

Posted 17 February 2014 - 12:34 PM

Look carefully at the coordinates you provided and the pattern in traversal.

 

Your "horizontal" cost (e.g. 0,0 to 1,0) should be higher than your "diagonal" cost (e.g. 0,0 to 0,1). The reason dividing dy by 2 in your first attempt appeared to help is that you made the relative cost of diagonals cheaper.

 

Don't just "try again and again." Look at your numbers and think about how to represent the costs that you want, and then write code that reflects that.

 

 

Also, it sounds like you're not actually implementing A* correctly, or don't fully understand the algorithm. There are two costs: the heuristic (which as Alvaro said is generally not the problem provided it is admissible) and the actual traversal cost. Chances are your problem is in your A* implementation in how you compute the actual traversal cost versus the values provided by your heuristic.


Edited by ApochPiQ, 17 February 2014 - 12:36 PM.


#9 Pink Horror   Members   -  Reputation: 1149

Like
0Likes
Like

Posted 17 February 2014 - 03:10 PM

How can I adjust my cost function? I just try again and again until I find something that matches with what I want?


Why don't you share with the forum the actual cost function that you use when you're building the path? The heuristic and the real cost have to be fixed together.

Also, because you're having trouble with an 8-way system, I think you should try to get 4 directions working correctly first. I'd like to know how that works out.

Another interesting experiment would be using a heuristic that always returned 0. You would have a slower path-finding function but it should work and rule out any heuristic issues.

#10 ferrous   Members   -  Reputation: 1921

Like
1Likes
Like

Posted 17 February 2014 - 05:03 PM

Yeah, I'm with ApochPiQ, I suspect the problem is that there are two functions to determine the next move, the cost to move to that new tile, and the heuristic to determine how close that move will get you to the goal.

 

For your case, you want to take the path that costs the least to move to (diagonals cost more) and yet yields the best H value, in your case the least distance to the goal.


Edited by ferrous, 17 February 2014 - 05:03 PM.


#11 GuiTeK   Members   -  Reputation: 140

Like
2Likes
Like

Posted 18 February 2014 - 02:51 PM

Well, since my last post there have been many changes. Here's the long story.

 

First of all, the screenshots I showed you didn't come from a program I coded. Actually, the program comes from here.

My pathfinding algorithm wasn't working as expected so I decided to search for one that would work as I wanted. Unfortunately, I didn't find anything for isometric tile maps with 8 directions possible. I then decided to modify the program I linked above to make it work with isometric tiles and with 8 directions. It was actually a bad idea because it took me time to understand how the pathfinding was implemented and the modifications I made were... quite messy (on top of that I'm not a Java programmer and it's written in Java sleep.png ).

 

Ok, so I decided to take back MY algorithm (implemented in C++) and try (one more time) to make it work.

 

[...] Also, it sounds like you're not actually implementing A* correctly, or don't fully understand the algorithm. There are two costs: the heuristic (which as Alvaro said is generally not the problem provided it is admissible) and the actual traversal cost. Chances are your problem is in your A* implementation in how you compute the actual traversal cost versus the values provided by your heuristic.

Yes there are 2 costs, thanks for reminding me! All this time, I don't know why but I never considered the "G" (known) cost. I focused on the "H" (heuristic) cost. Your answer, ferrous, helped me as well:

 

Yeah, I'm with ApochPiQ, I suspect the problem is that there are two functions to determine the next move, the cost to move to that new tile, and the heuristic to determine how close that move will get you to the goal.

 

For your case, you want to take the path that costs the least to move to (diagonals cost more) and yet yields the best H value, in your case the least distance to the goal.

After reading your post, I modified my heuristic function to a simple one (diffX + diffY):

int Pathfinder::calculateHeuristicCost(PathNode *node)
{
    Point cellPt = this->getCoordsFromCellId(node->CellId);
    Point goalPt = this->getCoordsFromCellId(m_goalCellId);

    int dx = std::abs(cellPt.X - goalPt.X);
    int dy = std::abs(cellPt.Y - goalPt.Y);

    return dx + dy;
}

and I worked on the function which calculates the G cost. I decided to penalize orthogonal moves by adding an extra cost. But then the question is: what cost should I add to orthogonal moves?

  • If the cost it too high, the algorithm will always prefer diagonal moves and it will result in longer paths sometimes.
  • If the cost is too low, the algorithm will always prefer orthogonal moves (as shown in the screenshots above) and it will result in longer paths as well.

After a few tries, I ended up with the values +10 for diagonal moves and +14 for orthogonal moves (which are common values for pathfinding, don't really know why, I read some things about distances and Pythagorean theorem).

const int ORTHOGONAL_COST = 14;
const int DIAGONAL_COST = 10;

int Pathfinder::calculateMoveCost(PathNode *parent, PathNode *node)
{
    const CellData &parentCellData = m_mapGrid.getCellDataFromId(parent->CellId);
    const CellData &nodeCellData = m_mapGrid.getCellDataFromId(node->CellId);

    if (this->getDiagonalAlignment(parentCellData, nodeCellData) != Direction::None)
        return parent->G + DIAGONAL_COST;
    else
        return parent->G + ORTHOGONAL_COST;

    return 0;
}

Result:  (I don't know why there is a black line in the middle, it doesn't matter).

As you can see, it works pretty well.

 

What do you think? Good/bad method?



#12 ApochPiQ   Moderators   -  Reputation: 15091

Like
2Likes
Like

Posted 18 February 2014 - 04:30 PM

Good work!

 

The reason you wound up with 10 and 14 is because of Pythagoras, as you noted: if a straight line costs 10 units, then the triangle formed by taking two straight moves also offers you a third move, the diagonal. By the Pythagorean theorem, the diagonal cost = sqrt(a*a + b*b) = sqrt(10*10 + 10*10) = sqrt(200) ~= 14.142.



#13 GuiTeK   Members   -  Reputation: 140

Like
0Likes
Like

Posted 19 February 2014 - 09:49 AM

Good work!

 

The reason you wound up with 10 and 14 is because of Pythagoras, as you noted: if a straight line costs 10 units, then the triangle formed by taking two straight moves also offers you a third move, the diagonal. By the Pythagorean theorem, the diagonal cost = sqrt(a*a + b*b) = sqrt(10*10 + 10*10) = sqrt(200) ~= 14.142.

Thank you for this explanation and for all your answers.

Thanks to everybody who posted in this thread too.

 

I can move on to the next part of my game now smile.png .






Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS