Hello everyone,
i’m making a horror game and i need to make an AI for the enemy.
I have the enemy patrolling through the level and chasing/attacking the player when he is in range.
using UnityEngine;
using System.Collections;
public class Chase2 : MonoBehaviour {
public Transform player;
public Transform head;
Animator anim;
private SphereCollider col;
private NavMeshAgent agent;
public Transform[] waypoints;
int currentWP = 0;
float rotspeed = 2f;
float speed = 1.9f;
RaycastHit hit;
Vector3 fwd;
void Start ()
{
agent = GetComponent<NavMeshAgent> ();
agent.autoBraking = false;
GotoNextPoint();
anim = GetComponent<Animator> ();
}
void GotoNextPoint()
{
if (waypoints.Length == 0)
return;
agent.speed = 2f;
agent.destination = waypoints [currentWP].position;
currentWP = Random.Range (0, waypoints.Length);
}
void Update ()
{
Vector3 direction = player.position - this.transform.position;
direction.y = 0;
float angle = Vector3.Angle (direction, head.forward);
if (waypoints.Length > 0) {
anim.SetBool ("IsIdle", false);
anim.SetBool ("IsWalking", true);
if (agent.remainingDistance < 0.5f)
GotoNextPoint ();
if (Vector3.Distance (player.position, this.transform.position) < 19 && angle < 60) {
agent.speed = 3.8f;
agent.destination = player.position;
this.transform.rotation = Quaternion.Slerp (this.transform.rotation,
Quaternion.LookRotation (direction), 3f);
if (direction.magnitude > 3) {
anim.SetBool ("IsRunning", true);
anim.SetBool ("IsAttacking", false);
anim.SetBool ("IsWalking", false);
agent.Resume ();
} else {
anim.SetBool ("IsRunning", false);
anim.SetBool ("IsAttacking", true);
anim.SetBool ("IsWalking", false);
agent.Stop (true);
}
} else {
anim.SetBool ("IsAttacking", false);
anim.SetBool ("IsRunning", false);
}
}
}
//This part should tell the enemy to open the door but it doesn't work,the tags are inverted,DoorOpened is a closed door
void OnTriggerStay (Collider other)
{
if (hit.collider.tag == "DoorOpened")
{
if (Physics.Raycast (transform.position, fwd,out hit, col.radius))
{
Animation Door = hit.collider.GetComponent<Animation> ();
Door.Play ("DoorOpened");
hit.collider.tag = "DoorClosed";
AudioSource CDoorClip = hit.collider.GetComponent<AudioSource> ();
CDoorClip.volume = 0.3f;
CDoorClip.Play ();
}
}
}
}
Since the level is a hotel,i need the enemy to be able to open doors,
i tried something like in the script but he just walk through doors without opening them.
Also how can i change the script so the enemy doesnt detect the player if he is behind a wall?
thanks
Costa