Alright so i am making a little horror game and i want the enemy to patrol the area, around objects and up and down hills and stuff (my terrain isnt just flat). And when i go in the enemies line of sight or i get to close it comes after me and when i get to far it continues patrolling. I am using this code
using UnityEngine;
using System.Collections;
public class Chase : MonoBehaviour {
public Transform player;
public Transform head;
static Animator anim;
string state = "patrol";
public GameObject[] waypoints;
int currentWP = 0;
float rotSpeed = 0.2f;
float speed = 0.02f;
float accuracyWP = 5.0f;
// Use this for initialization
void Start ()
{
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
Vector3 direction = player.position - this.transform.position;
direction.y = 0;
float angle = Vector3.Angle(direction, head.up);
if(state == "patrol" && waypoints.Length > 0)
{
anim.SetBool("isIdle", false);
anim.SetBool("isWalking", true);
if(Vector3.Distance(waypoints[currentWP].transform.position, transform.position) < accuracyWP)
{
currentWP++;
if(currentWP >= waypoints.Length)
{
currentWP = 0;
}
}
//rotate towards waypoint
direction = waypoints[currentWP].transform.position - transform.position;
this.transform.rotation = Quaternion.Slerp(transform.rotation,
Quaternion.LookRotation(direction), rotSpeed * Time.deltaTime);
this.transform.Translate(0, 0, Time.deltaTime * speed);
}
if (Vector3.Distance(player.position, this.transform.position) < 20 && (angle < 30 || state == "pursuing"))
{
state = "pursuing";
this.transform.rotation = Quaternion.Slerp(this.transform.rotation,
Quaternion.LookRotation(direction), rotSpeed * Time.deltaTime);
if (direction.magnitude > 5)
{
this.transform.Translate(0,0,Time.deltaTime * speed);
anim.SetBool("isWalking", true);
}
else
{
anim.SetBool("isWalking", false);
}
}
else
{
anim.SetBool("isIdle", true);
anim.SetBool("isWalking", false);
state = "patrol";
}
}
}
I got it off this video right hear. Simple Waypoint Pathfinding with the Line of Sight AI - YouTube
The problem is that since my terrain isnt flat the enemy just floats a little bit above the ground and also i have 19 waypoints that zig zag in and out around the “town”. So since the ground isnt flat and theirs obstacles the enemy either doesnt move or he floats around. I have tried adding a rigid body and checking gravity but all that does is makes the enemy fall over. So what i need is for someone to maybe edit this script for me so that the enemy ai will be able to go to all the waypoints, not float and stay on the ground, and when i get into the line of site he will stop patrolling and chase me and when i get to far he will stop and continue patrolling.
** I am not good at scripting so if you just type what i need without adding it to the whole script i wont know what to do**
Thanks!!