- Home /
What is the easiest way to make an object notice another?
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.
var myEnemy;
function OnTriggerEnter (enter : Collider) { if(enter.gameObject.tag == "Enemy") { myEnemy = enter.transform; } }
function Update() { transform.LookAt(myEnemy.position); }
Answer by jtbentley · Sep 07, 2010 at 01:29 PM
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 :)
An additional note, a moving object won't reliably trigger OnBlah collision events unless it has a rigidbody - so add a Rigidbody to your enemies. You can set it to is$$anonymous$$inematic to continue controlling them through script, too.
Answer by AliAzin · Sep 06, 2010 at 06:55 AM
OnTriggerEnter is easier to use and has much better performance.
Answer by james flowerdew · Sep 09, 2010 at 12:25 PM
Could you ompare the transform.positions and use distance? If you can, this is very cheap and effective.
if((transform.position-vBadObject.transform.position).magnitude<myAlertDistance){
StartFiring();
}
Your answer