A* Pathfinding - Path Cancels when multiple enemies spawn?!
Hi,
I'm making a game for a project at School that is due Friday and I am having some issue with regards to the pathfinding algorithm I'm using.
The algorithm works great when there is only 1 Enemy, it follows the player constantly and works very efficiently. However, one issue I am having is that when I spawn multiple instances of the enemy, with the pathfinding script and the seeker script, after around 1-2 seconds, they all stop pathfinding and the path cancels?!
Could I have some insight as to how to fix this please.
Thanks Very Much!
public class EnemyAIBasic : MonoBehaviour {
public Transform target;
public GameObject Character;
public float updateRate = 2f;
Animator anim;
private Seeker seeker;
private Rigidbody2D rb2d;
public Pathfinding.Path path;
public float speed = 300f;
public ForceMode2D fMode;
[HideInInspector]
public bool pathIsEnded = false;
public float nextWaypointDist = 3f;
private int currentWaypoint = 0;
void Start() {
Character = GameObject.FindGameObjectWithTag ("Char");
target = Character.transform;
seeker = GetComponent<Seeker> ();
rb2d = GetComponent<Rigidbody2D> ();
if (target == null) {
UnityEngine.Debug.LogError ("No player found.");
return;
}
seeker.StartPath (transform.position, target.position, OnPathComplete);
//StartCoroutine (UpdatePath ());
}
void FixedUpdate(){
//target = Character.transform;
if (target == null) {
return;
}
if (path == null) {
return;
}
if (currentWaypoint >= path.vectorPath.Count) {
if (pathIsEnded)
return;
UnityEngine.Debug.Log ("End of path reached.");
pathIsEnded = true;
return;
}
pathIsEnded = false;
Vector3 dir = (path.vectorPath [currentWaypoint] - transform.position).normalized;
dir *= speed * Time.fixedDeltaTime;
rb2d.AddForce (dir, fMode);
float dist = Vector3.Distance (transform.position, path.vectorPath [currentWaypoint]);
if (dist < nextWaypointDist) {
currentWaypoint++;
}
}
IEnumerator UpdatePath (){
if (target == null) {
yield return false;
}
seeker.StartPath (transform.position, target.position, OnPathComplete);
yield return new WaitForSeconds (1f / updateRate);
StartCoroutine (UpdatePath());
}
public void OnPathComplete(Pathfinding.Path p){
UnityEngine.Debug.Log ("We got a path. Was there an Error?" + p.error);
if (!p.error) {
path = p;
currentWaypoint = 0;
}
}
}
I don't know what Pathfinding.Path is. Is it a Unity class?
It looks like all enemies use the same path reference. Are you sure this is ok?
Your answer
Follow this Question
Related Questions
A* pathfinging problem 0 Answers
A* finding nearest Object 0 Answers
2D Platformer Enemy Pathfinding 0 Answers
2D platformer AI 0 Answers