Академический Документы
Профессиональный Документы
Культура Документы
Mar 22
Let's take in account that our map is 1000x500 pixels divided in 50x25
blocks. I am using Magic Numbers to make it as widely usable as possible.
Then I make a new structure to represent each Node (square) on the map.
Since later on I am putting this structure in to a set, I first need to overload
https://dev.to/jansonsa/a-star-a-path-finding-c-4a4h Page 1 of 7
A Star (A*) Path Finding C++ - DEV Community ! " 12/25/18, 1(54 PM
the operator < to tell the set which value we compare, since it is an ordered
sequence.
struct Node
{
int y;
int x;
int parentX;
int parentY;
float gCost;
float hCost;
float fCost;
};
inline bool operator < (const Node& lhs, const Node& rhs)
{//We need to overload "<" to put our struct into a set
return lhs.fCost < rhs.fCost;
}
static bool isValid(int x, int y) { //If our Node is an obstacle it is not val
int id = x + y * (X_MAX / X_STEP);
if (world.obstacles.count(id) == 0) {
if (x < 0 || y < 0 || x >= (X_MAX / X_STEP) || y >= (Y_MAX / Y_STEP
return false;
}
return true;
}
return false;
}
https://dev.to/jansonsa/a-star-a-path-finding-c-4a4h Page 2 of 7
A Star (A*) Path Finding C++ - DEV Community ! " 12/25/18, 1(54 PM
}
return false;
}
This is where it starts to differ from Dijkstra's. We use H cost and F cost so
we first check nodes that move towards our destination and only then the
ones that move away from it.
https://dev.to/jansonsa/a-star-a-path-finding-c-4a4h Page 3 of 7
A Star (A*) Path Finding C++ - DEV Community ! " 12/25/18, 1(54 PM
allMap[x][y].y = y;
closedList[x][y] = false;
}
}
vector<Node> openList;
openList.emplace_back(allMap[x][y]);
bool destinationFound = false;
x = node.x;
y = node.y;
closedList[x][y] = true;
https://dev.to/jansonsa/a-star-a-path-finding-c-4a4h Page 4 of 7
A Star (A*) Path Finding C++ - DEV Community ! " 12/25/18, 1(54 PM
You might notice that we're still missing one function makePath. That is
where we follow each parent starting from our destination node till we
https://dev.to/jansonsa/a-star-a-path-finding-c-4a4h Page 5 of 7
A Star (A*) Path Finding C++ - DEV Community ! " 12/25/18, 1(54 PM
reach our starting point while putting them inside a vector, we're later
going to pass to aStar and from there to anyplace else we might find it
useful.
}
path.push(map[x][y]);
while (!path.empty()) {
Node top = path.top();
path.pop();
usablePath.emplace_back(top);
}
return usablePath;
}
catch(const exception& e){
cout << e.what() << endl;
}
}
First we create a node for starting position as well as one for the
destination and then run the algorithm.
https://dev.to/jansonsa/a-star-a-path-finding-c-4a4h Page 6 of 7
A Star (A*) Path Finding C++ - DEV Community ! " 12/25/18, 1(54 PM
Node player;
player.x = X / X_STEP;
player.y = Y / Y_STEP;
Node destination;
destination.x = e->X / X_STEP;
destination.y = e->Y / Y_STEP;
https://dev.to/jansonsa/a-star-a-path-finding-c-4a4h Page 7 of 7