Tower is targeting wrong enemies
I've tried a couple different methods...
My first solution was to use an array of enemies. Each time the prefab is instantiated, it is added to the array and the tower targets the enemies from that array. My mistake there was that I was using a for loop so that the tower could target each enemy in sequence, but what I got was simultaneously, i.e. every enemy within range would be attacked at the same time.
So I abandoned the array and tried using an OnTriggerEnter() solution, and now what I have is the tower targeting the enemy to most recently enter the trigger. Not very useful if you're trying to keep your base alive.
What are some other solutions I might try? Ideally, the tower would target the creep closest to the base, but right now I'd settle for the tower attacking a single enemy until it either dies or goes out of range.
Solved using a Queue data structure.
class TowerLogic ...
...
void Update () {
try {
this.m_target = this.m_gameController.m__creeps.Peek ();
} catch {
return; //prevents console errors when the Queue is empty
}
if (this.m_target != null && Time.time > this.m_nextFire) {
this.m_nextFire = Time.time + this.m_fireRate;
Debug.Log ("Ready to fire");
SpawnProjectile (this.m_target);
}
}
private void OnTriggerEnter (Collider other) {
if (other.gameObject.CompareTag ("Creeps")) {
CreepLogic targetScript = other.gameObject.GetComponent<CreepLogic> ();
targetScript.OnCreepDeath += FindNextTarget;
this.m_gameController.m__creeps.Enqueue (other.gameObject);
Debug.Log ("Creep Detected");
}
}
private void OnTriggerExit (Collider other) {
if (other.gameObject.CompareTag ("Creeps")) {
this.m_hasTarget = false;
CreepLogic targetScript = other.gameObject.GetComponent<CreepLogic> ();
targetScript.OnCreepDeath -= FindNextTarget;
this.m_gameController.m__creeps.Dequeue();
Debug.Log ("Creep out of range");
}
}
void FindNextTarget () {
this.m_gameController.m__creeps.Dequeue ();
}
...
and
class CreepLogic ...
....
public delegate void CreepDelegate ();
public event CreepDelegate OnCreepDeath;
....
void OnDestroy () {
if (OnCreepDeath != null) OnCreepDeath ();
}
Your answer
Follow this Question
Related Questions
Tower defence targeting first enemy 0 Answers
Shoot towards target 0 Answers
What should I do? 2 Answers
Getting a pivoted look at in 2D 2 Answers
Navmesh according to tile map sprites? 0 Answers