Moving Enemy Along A Star Path
Ok so I am trying to implement some A* pathfinding in a project I am doing. I have been following along with some tutorials explaining the algorithm and setting it up. I have that all done and I believe the pathfinding is working properly and populating a path which is a Stack. The part where I am struggling is how do I get my enemy or player to move along that path? As in, how do I get them to move to the first Vector3Int in the stack, followed by second, and so on for the length of the stack? In another video the same person I was following was implementing the algorithm for enemy pathfinding and was moving the enemy in the update method using
transform.parent.position = Vector2.MoveTowards(transform.parent.position, destination, moveSpeed * Time.deltaTime);
Now the problem is that between the set up of the pathfinding algorithm and his implementation of it, he changed alot of code, but didnt say what, and didnt offer any files for download. I am currently using this...
transform.position = Vector3.MoveTowards(transform.position, destination, moveSpeed * Time.deltaTime);
And it has nothing to do with pathfinding. It just moves my enemy straight onto the player. I have been using this line to move my player and enemies for a long time while I was playtesting other features, before I ever tried to do pathfinding. So naturally I am quite confused when this other person can use almost the same code as me but be moving along a path, whereas mine just goes straight to the target without any kind of path. The only thing I can think of is that in this other persons code they are using the Stack to set the "destination" in the above code and updating it after every move for the whole stack. If thats the case It shouldnt be to hard to do it. However I am fairly new to how stacks work and how to use the information in them. So if somebody could let me know how to use my stack of grid coordinates to make a transform move along them that would be fantastic. Thanks!
Answer by tylerdtrudeau · Mar 12, 2021 at 05:01 AM
Alright well I figured it out and it was really easy so here it is if anyone else wants to know how I did it.
if (path.count > 0)
{
Tile t = path.Peek(); // get value of top item in stack
Vector3 target = t.transform.position;
if (Vector3.Distance(transform.position, target) >= 0.05f)
{
// move towards target
}
else
{
transform.position = target; // just to make sure centered on tile
path.Pop(); // remove top item of stack
}
}
This looks at the top of stack, sets as destination, moves to it, removes it from stack, then repeats until stack is empty.
Your answer
Follow this Question
Related Questions
astar pathfinding with groups 0 Answers
How to know which point that AI picked to move to? (A* Pathfinding) 0 Answers
How do I make AI objects not walk on top of each other? 5 Answers
Astar Pathfinding check if areas are connected (Please Help!) 0 Answers
Choosing non null values from arrays for pathfinding 2 Answers