I have a spawner spawning my enemies. I then have turrets positioned on my 2D world. I need the turrets to shoot at the closest enemy. The problem I run into is i am trying to use transform.LookAt();
I cannot do this because if i write out this code.
#pragma strict
public var target : Transform;
function Update ()
{
transform.LookAt(target);
}
Using this method, I define my “target” through the Inspector. In the spawner, I use a prefab(for my enemy) to spawn them. It creates in my hierarchy it creates “Enemy(Clone)”.
At this point my turret doesn’t know what to look at as “Enemy” doesn’t exist in my scene.
How would i be able to get my turret, to look at my moving “Enemy(Clone)”.
Do you always just want it to target the most recent thing coming from the spawner? If that’s the case just write a public static targetAcquision method in your turret class and then call that method via the class as part of the enemies instantiation process.
You could also track all enemies in the scene and distances and etc and then switch between them based on any number of conditions. However the simple fix to what you’re asking it to fire off some kind of method to update the turret class when a new enemy has entered the game.
The actual problem here is: how to select the enemy? Usually, a trigger centered at the turret position is used to detect when enemies enter its range, and adds each new enemy to a list. The target variable is set to the nearest one: look at it and open fire until the enemy drops dead, then remove the corpse from the list and set the target to the closest one, look at it and open fire etc.
Add a sphere collider to the turret, set its radius to the desired range and check Is Trigger, then attach the script below to the turret:
import System.Collections.Generic;
private var enemies = new List.<Transform>(); // create the list
private var target: Transform;
function OnTriggerEnter(other: Collider){
// NOTE: remember to tag the enemies as "Enemy"!
if (other.CompareTag("Enemy")){ // if enemy entered trigger...
enemies.Add(other.transform); // add to the list
}
}
function Update(){
if (target){ // if target still alive...
transform.LookAt(target); // look at him
// shoot at the bastard! call
// your shoot function here
}
else { // target dead: find the closest one
target = FindClosestEnemy();
}
}
function FindClosestEnemy(): Transform {
// references to dead enemies become null, thus
// let us remove the corpses from the list:
while (enemies.Remove(null));
// find the closest enemy, if any:
var here: Vector3 = transform.position;
var minDist: float = Mathf.Infinity; // init minDist to max value
var closest: Transform = null; // assume worst case
for (var enemy: Transform in enemies){
var dist: float = Vector3.Distance(enemy.position, here);
if (dist < minDist){ // if closest than minDist...
closest = enemy; // this is our closest enemy by now
minDist = dist; // save its distance
}
}
return closest; // return the nearest enemy, or null if none
}