- Home /
Enemy Detection Area
I got an enemy that follows the player and explodes on impact (Creeper from MineCraft). Now the problem is that he follows the player as soon as the game starts, I want him to only follow the player when the player is close to him. I tried to use an invisible box for the detection area but it didn't work. I get no errors, and I get no "detected!" print.
var target : Transform;
var moveSpeed = 5;
var rotationSpeed = 5;
var myTransform : Transform;
var Detect : boolean = false;
function Awake()
{
myTransform = transform;
}
function Start()
{
target = GameObject.FindWithTag("Player").transform;
}
function OnTriggerEnter(other : Collider)
{
if (other.tag == "Player")
{
Detect = true;
print ("detected!");
}
}
function Update () {
if (Detect == true)
{
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
}
also, If you got some other method I can use other than collision, please tell me.
Answer by robertbu · Feb 27, 2013 at 04:39 PM
Just compare your distance to the player distance each frame. If you want to be slightly more efficient, you can use distance squared.
function Update () {
if ((target.transform.positon - transform.position).sqrMagnitude < someDistanceSquared)
Detect = true;
if (Detect)
{
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
}
Thanks for the method, but I still need a certain area, because if the Player is above the Enemy he will still be detected, I don't want that. Also I need the flexibility of the area box so I can make things like laser traps and such. So I will be happy if someone knows how to make the area box method work.
Usually this problem is caused by neither object having a rigidbody. Either the game object with the collider or the target has to have a Rigidbody.
if the Player is above the Enemy he will still be detected
I guess if he is on a different level.
You could use a linecast between the enemy and the player to check if there is any collider in between, if so it means the enemy cannot see the player.