I’ve built basic pathfinding in my code with this Brackeys tutorial, and it seems Brackeys made a mistake somewhere because my AI is always in create-path/follow-target states, it never stops. People on youtube say that the problem is in incrementing currentWaypoint, but I can’t figure out why. Here’s the code itself.
public Transform target;
public float speed = 200f;
public float nextWaypointDistance = 3f;
Path path;
int currentWaypoint;
Seeker seeker;
Rigidbody2D rb;
void Start()
{
seeker = GetComponent<Seeker>();
rb = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
InvokeRepeating("UpdatePath", 0f, 1f);
}
void UpdatePath()
{
if(seeker.IsDone())
seeker.StartPath(rb.position, target.position, OnPathComplete);
}
void OnPathComplete(Path p)
{
if (!p.error)
{
path = p;
currentWaypoint = 0;
}
}
void FixedUpdate()
{
if (path == null)
return;
if (currentWaypoint >= path.vectorPath.Count)
{
reachedEndOfDestination = true;
return;
}
else
{
reachedEndOfDestination = false;
}
Vector2 direction = ((Vector2)path.vectorPath[currentWaypoint] - rb.position).normalized;
Vector2 force = direction * speed * Time.deltaTime;
rb.AddForce(force);
float distance = Vector2.Distance(rb.position, path.vectorPath[currentWaypoint]);
if (distance < nextWaypointDistance)
currentWaypoint++;
}