Hey, I've been trying to make a TD game and one big problem I've run into is getting the tower to notice the enemies, which is easier? RayCast or OnTriggerEnter?
heres the script I've been working on. but it doesn't work. its applied to a trigger sphere which has the towers top part as its child.
Well that should work... Except I'd specify the variable at the top.. Just because it's a good habit to have. I would probably also have a boolean so the tower doesn't look unless a target is acquired.
var hasTarget = false;
var myEnemy : Transform;
private var myTransform : Transform; // Cache the transform to reduce slow get-component calls
function Start()
{
myTransform = transform;
}
function OnTriggerEnter (enter : Collider)
{
if(enter.gameObject.tag == "Enemy" && !hasTarget) // Don't want to acquire a target if we still have one
{ myEnemy = enter.transform;
hasTarget = true;
}
}
function Update()
{
if (hasTarget) myTransform.LookAt(myEnemy.position);
}
Also worthy of note - both objects need colliders for this to work, and at least one has to be set to trigger :)