hello!
i have some trouble to trying to build a simple Ai system where the NPC is Run away from the player if it’s facing him otherwise it will try to go to the player position to eat him
but it doesn’t work as i want, it will run away but will freeze to the corner of map, and will not go to eat player if it’s not facing him… what i’m missing up?
using UnityEngine;
using System.Collections;
public class TunAway : MonoBehaviour {
private Transform player;
private UnityEngine.AI.NavMeshAgent myNMagent;
private float nextTurnTime;
private Transform startTransform;
public float multiplyBy;
// Use this for initialization
void Start () {
player = GameObject.FindGameObjectWithTag ("Player").transform;
myNMagent = this.GetComponent<UnityEngine.AI.NavMeshAgent> ();
RunFrom ();
}
// Update is called once per frame
void Update () {
//if is not facing got to eat him
if(!ISFacing())
{
GotToEat();
Debug.Log("is not facing here");
}
else
{
RunFrom ();
}
}
public void RunFrom()
{
startTransform = transform;
transform.rotation = Quaternion.LookRotation(transform.position - player.position);
Vector3 runTo = transform.position + transform.forward * multiplyBy;
UnityEngine.AI.NavMeshHit hit;
UnityEngine.AI.NavMesh.SamplePosition(runTo, out hit, 20, 1 << UnityEngine.AI.NavMesh.GetAreaFromName("Walkable"));
transform.position = startTransform.position;
transform.rotation = startTransform.rotation;
myNMagent.SetDestination(hit.position);
}
private void GotToEat()
{
myNMagent.SetDestination(player.transform.position);
}
private bool ISFacing()
{
float dot = Vector3.Dot(transform.position,(player.position - transform.position).normalized);
if( dot < 0.79f)
{
return true;
}
else
return false;
}
}