x


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); }

more ▼

asked Sep 06 '10 at 06:30 AM

Jason Hamilton gravatar image

Jason Hamilton
445 68 73 80

(comments are locked)
10|3000 characters needed characters left

3 answers: sort voted first

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 :)

more ▼

answered Sep 07 '10 at 01:29 PM

jtbentley gravatar image

jtbentley
579 3 4 16

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 isKinematic to continue controlling them through script, too.

Oct 20 '10 at 06:25 AM Loius
(comments are locked)
10|3000 characters needed characters left

OnTriggerEnter is easier to use and has much better performance.

more ▼

answered Sep 06 '10 at 06:55 AM

AliAzin gravatar image

AliAzin
2.5k 41 56 79

(comments are locked)
10|3000 characters needed characters left

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();
}
more ▼

answered Sep 09 '10 at 12:25 PM

james flowerdew gravatar image

james flowerdew
37 3 4 8

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x3460
x984
x336

asked: Sep 06 '10 at 06:30 AM

Seen: 592 times

Last Updated: Jul 16 '11 at 11:53 AM