I am simply trying to have my enemy follow my character with the help of this script i put together. But the enemy won't detect me at all:
//object to be followed
var detectObject: Transform;
var standing = false;
var attackSpeed = 6;
private var characterController : CharacterController;
characterController = GetComponent(CharacterController);
private var nextFire = 0.0;
var fireRate = .5;
var fieldOfViewRange : float;
var minPlayerDetectDistance : float;
var rayRange : float;
private var rayDirection = Vector3.zero;
function Start()
{
detectObject = GameObject.FindWithTag("Player").transform;
animation.wrapMode = WrapMode.Loop;
animation.Play("idle");
animation["run"].speed = 1;
}
function Update ()
{
if (detectObject)
{
if(CanSeePlayer())
{
//print("attack");
Debug.Log("SEE YOU");
animation.CrossFade("run");
attack();
return;
}
else
{
GetComponent(SmoothLookAt).enabled = false;
animation.CrossFade("idle");
}
}
}
function attack()
{
var nextFireTime = 0;
var dist = Vector3.Distance(detectObject.position, transform.position);
if(dist<5)
{
//Debug.Log("HIT");
animation.CrossFade("attack");
characterController.SimpleMove(Vector3.forward*0);
if(Time.time > nextFire)
{
nextFire = Time.time + fireRate;
detectObject.SendMessage("ApplyDamage" , 1);
}
}
else
{
direction = transform.TransformDirection(Vector3.forward * attackSpeed);
characterController.SimpleMove(direction);
GetComponent(SmoothLookAt).enabled = true;
//GetComponent(ConstantForce).enabled = true;
}
}
function CanSeePlayer() : boolean
{
var hit : RaycastHit;
rayDirection = detectObject.transform.position - transform.position;
var distanceToPlayer = Vector3.Distance(transform.position, detectObject.transform.position);
if(Physics.Raycast (transform.position, rayDirection, hit)){ // If the player is very close behind the enemy and not in view the enemy will detect the player
if((hit.transform.tag == "Player") && (distanceToPlayer <= minPlayerDetectDistance)){
Debug.Log("Caught player sneaking up behind!");
return true;
}
}
if((Vector3.Angle(rayDirection, transform.forward)) < fieldOfViewRange){ // Detect if player is within the field of view
if (Physics.Raycast (transform.position, rayDirection, hit, rayRange)) {
if (hit.transform.tag == "Player") {
Debug.Log("Can see player");
return true;
}else{
Debug.Log("Can not see player");
return false;
}
}
}
}
function OnDrawGizmosSelected ()
{
// Draws a line in front of the player and one behind this is used to visually illustrate the detection ranges in front and behind the enemy
Gizmos.color = Color.magenta; // the color used to detect the player in front
Gizmos.DrawRay (transform.position, transform.forward * rayRange);
Gizmos.color = Color.yellow; // the color used to detect the player from behind
Gizmos.DrawRay (transform.position, transform.forward * -minPlayerDetectDistance);
}
any ideas please?