I have a code that when I click over a character and then on another point, the character will find a Path using A* project and walk to that point. While the character is moving, it won’t be able to attack.
I realized that when the character is staying still, sometimes it won’t be able to attack. Also I realized that when it is moving, sometimes it will be able to attack.
After many tests and Debugs.logs, I tracked down the location that this was being changed.
This is the code and the place where it is being changed:
void Update()
{
// check if path is null
if (path == null)
{
return;
}
// check if we have reached the end
if (currentWayPoint >= path.vectorPath.Count)
{
return;
}
//Some other code
}
By checking the currentWayPoint if it is larger than path.vectorPath.Count, I expect to know whether I have reached the end of the path, also if I have not told the character to move, I expect the path to be null. Notice that this part of the code is also taken from Brackeys.
I added an else Statement after the if statement, and when it is still, sometimes it will go to the else statement. While if the character is walking, sometimes it goes into the if statement (as if the character has already finished the path).
There are some callbacks available to test for when a seeker reached the end of the path let me mock up some sample code.
Just to clarify, the expected behavior is:
when standing the character can attack
when moving the character does not attack
public bool canAttack = true; //initial value is true because they are not moving
void Start(){
seeker = this.GetCompoenent<Seeker>();
//pathCallback is called when the seeker reaches it's destination
seeker.pathCallback = OnPathCompleted;
//the postProcessPath is called when the path is found
seeker.postProcessPath = OnPathFound;
}
//this is called when the user clicks on a position and begins a move
public void StartMove(Vector3 positionToMoveTo){
//we don't disable movement here because a path is not found yet
seeker.StartPath(this.transform.position, positionToMoveTo);
}
//this is called when a path is found after calling start path
public void OnPathFound(){
canAttack = false;
}
//this is called when the seeker reaches it's destination
public void OnPathComplete(Path p){
canAttack = true;
}
void Update(){
if(canAttack){
//do your attack
}
}
Hopefully the comments and such help explain what I’m doing if you have questions let me know!
Generally one would request a path and then only store it once the OnPathComplete callback is called. If this parameter did not exist one would have to keep track of all the paths in flight which would be error prone.