(Keep in mind that this is in a 3D environment)
I have an enemy that uses a raycast to find where the player is. If the enemy finds the player, the enemy attacks and pursues the player. I want it so that if the enemy’s raycast does not pick up the player with a certain amount of time, the enemy will stop pursuing the player.
This is what I have so far. The actual attack behavior of the enemy is handled in a separate script at the moment
using UnityEngine;
using System.Collections;
public class LookAtPlayer : MonoBehaviour {
private GameObject Player;
private RaycastHit Hit;
public bool SeesPlayer;
void FixedUpdate ()
{
Player = GameObject.FindGameObjectWithTag("Player");
var targetRotation = Quaternion.LookRotation (Player.transform.position - transform.position, Vector3.up);
Vector3 RayDirection = transform.TransformDirection (Vector3.forward);
Debug.DrawRay(transform.position, RayDirection, Color.green);
if (Physics.Raycast (transform.position, RayDirection, out Hit))
{
if (Hit.transform == Player.transform)
{
Debug.Log("enemy sees player");
SeesPlayer = true;
if(Time.frameCount == 120 && Hit.transform != Player.transform)
{
SeesPlayer = false;
}
}
else if (Hit.transform != Player.transform)
{
Debug.Log("enemy can't see player");
SeesPlayer = false;
}
}
transform.rotation = Quaternion.Lerp (transform.rotation, targetRotation, Time.deltaTime * 100);
}
}