I'm currently implementing an A* Algorithm for my Unity project. I found this entry on stackoverflow, but its not telling me how to solve my problem.
https://stackoverflow.com/questions/32205891/a-star-algorithm-in-a-3d-configuration-space
I'm not sure about the math required to calculate the distance cost correctly. How to properly implement this in 3-dimensional space?
In 2D space it is clear how to implement:
public static int CalculateDistanceCost(int3 a, int3 b)
{
int xDistance = math.abs(a.x - b.x);
int yDistance = math.abs(a.y - b.y);
int remaining = math.abs(xDistance - yDistance);
return 14 * math.min(xDistance, yDistance) + 10 * remaining;
}
However in 3d space it is unclear to me how to calculate it:
public struct AStarMath
{
public static int CalculateDistanceCost(int3 a, int3 b)
{
int xDistance = math.abs(a.x - b.x);
int yDistance = math.abs(a.y - b.y);
int zDistance = math.abs(a.z - b.z);
int remaining = math.abs(xDistance - yDistance - zDistance);
return 14 * math.min(math.min(xDistance, yDistance), zDistance) + 10 * remaining;
}
}
My neighbour cells are set up as follows:
int3 neighbours = new int3[]
{
//X(width),y(height),z(depth)
new int3(-1, -1, -1), //Left, Bottom, Front
new int3(0, -1, -1), //Middle, Bottom, Front
new int3(+1, -1, -1), //Right, Bottom, Front
new int3(-1, 0, -1), //Left, Middle, Front
new int3(0, 0, -1), //Middle, Middle, Front
new int3(+1, 0, -1), //Right, Middle, Front
new int3(-1, +1, -1), //Left, Top, Front
new int3(0, +1, -1), //Middle, Top, Front
new int3(+1, +1, -1), //Right, Top, Front
new int3(-1, -1, 0), //Left, Bottom, Middle
new int3(0, -1, 0), //Middle, Bottom, Middle
new int3(+1, -1, 0), //Right, Bottom, Middle
new int3(-1, 0, 0), //Left, Middle, Middle
//Middle, Middle, Middle (0,0,0) -> dont add, were already here
new int3(+1, 0, 0), //Right, Middle, Middle
new int3(+1, +1, 0), //Left, Top, Middle
new int3(0, +1, 0), //Middle, Top, Middle
new int3(+1, +1, 0), //Right, Top, Middle
new int3(-1, -1,+1), //Left, Bottom, Back
new int3(0, -1,+1), //Middle, Bottom, Back
new int3(+1, -1,+1), //Right, Bottom, Back
new int3(-1, 0,+1), //Left, Middle, Back
new int3(0, 0,+1), //Middle, Middle, Back
new int3(+1, 0,+1), //Right, Middle, Back
new int3(-1, +1,+1), //Left, Top, Back
new int3(0, +1,+1), //Middle, Top, Back
new int3(+1, +1,+1), //Right, Top, Back
};
As you can see in this image, my enemy (magenta) now takes a weird path, but will always find a path towards target (blue).

