I am currently working on a test ai, I want it to follow the player. I got a working one, however I was updating the path too suddenly, which causes the ai to freeze and not move. This is the code I am using, what is a better way of making the ai follow the player?
`using UnityEngine;
using System.Collections;
using Pathfinding;
public class neww : MonoBehaviour
{
public Vector3 targetPosition;
private Seeker seeker;
private CharacterController controller;
public Path path;
public float speed = 100;
public float nextWaypointDistance = 3;
private int currentWaypoint = 0;
private bool chasePlayer = true;
private Vector3 oldPosition;
public void Start()
{
StartCoroutine(WaitTime());
oldPosition = GameObject.Find("Player").transform.position;
}
IEnumerator WaitTime()
{
while (chasePlayer == true)
{
Debug.Log("loop is working");
targetPosition = GameObject.Find("Player").transform.position;
if (oldPosition != targetPosition)
{
oldPosition = targetPosition;
seeker = GetComponent<Seeker>();
controller = GetComponent<CharacterController>();
seeker.StartPath(transform.position, targetPosition, OnPathComplete);
Debug.Log("working");
}
yield return new WaitForSeconds(0.2f);
}
}
public void OnPathComplete(Path p)
{
Debug.Log("Yay, we got a path back. Did it have an error? " + p.error);
if (!p.error)
{
path = p;
currentWaypoint = 0;
}
}
public void FixedUpdate()
{
if (path == null)
{
return;
}
if (currentWaypoint >= path.vectorPath.Count)
{
//Debug.Log("End Of Path Reached");
return;
}
Vector3 dir = (path.vectorPath[currentWaypoint] - transform.position).normalized;
dir *= speed * Time.fixedDeltaTime;
controller.SimpleMove(dir);
if (Vector3.Distance(transform.position, path.vectorPath[currentWaypoint]) < nextWaypointDistance)
{
currentWaypoint++;
return;
}
}
}
`