This question was
closed Feb 22, 2018 at 11:00 PM by
PaincideStudio for the following reason:
I solved this.
Question by
PaincideStudio · Feb 19, 2018 at 08:01 AM ·
triggernavmeshnavmeshagentbooldestination
NavmeshDestination not changing.
Hello.
I'm trying to make AI wandering and chase the player when player stays in collider.
I made AI wandering and also found that trigger and raycasting works fine.
But the problem is it should change the target Destination to Player.transform.position when player is in trigger and AI raycasts player.
I set the lookAt to make raycasting more perfect, but it just wanders...
What should I change from the script?
I set the bool to change the destination when changing but not working.
How can I change the Destination when chasing?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class BeuBaeMovement : MonoBehaviour {
public Transform sight;
public GameObject Player;
NavMeshAgent navMeshAgent;
NavMeshPath path;
public float timeForNewPath;
bool inCoRoutine;
Vector3 target;
bool validPath;
bool wandering;
public Animator anim;
public Animator door;
void Start()
{
navMeshAgent = GetComponent<NavMeshAgent> ();
path = new NavMeshPath ();
navMeshAgent.speed = speedController.speedValue;
wandering = true;
}
void Update()
{
if (wandering == true && inCoRoutine == false)
StartCoroutine (DoSomething ());
if (navMeshAgent.velocity.magnitude > 1.0f)
{
anim.SetBool ("IsWalking", true);
}
else
{
anim.SetBool ("IsWalking", false);
}
Ray sightray = new Ray (sight.position, sight.forward);
RaycastHit sighthit;
if (Physics.Raycast (sightray, out sighthit, 5.0f, ~(1 << 9)))
{
if (sighthit.collider.CompareTag ("Player"))
{
navMeshAgent.destination = Player.transform.position;
Debug.Log ("here");
}
}
Ray ray = new Ray (sight.position, sight.forward);
RaycastHit doorhit;
if (Physics.Raycast (ray, out doorhit, 1.0f,~(1<<9)))
{
if (doorhit.collider.name == "BeuBaeDoor")
{
door.SetBool ("Open", true);
}
}
}
Vector3 getNewRandomPosition()
{
float x = Random.Range (-120, 120);
float z = Random.Range (-120, 120);
Vector3 pos = new Vector3 (x, 0, z);
return pos;
}
IEnumerator DoSomething()
{
inCoRoutine = true;
yield return new WaitForSeconds (timeForNewPath);
GetNewPath ();
validPath = navMeshAgent.CalculatePath (target,path);
while (!validPath)
{
yield return new WaitForSeconds (0.01f);
GetNewPath ();
validPath = navMeshAgent.CalculatePath (target,path);
}
inCoRoutine = false;
}
void GetNewPath()
{
target = getNewRandomPosition ();
navMeshAgent.SetDestination (target);
}
void OnTriggerStay()
{
sight.LookAt (Player.transform.position);
Ray look = new Ray(sight.position, sight.forward);
RaycastHit lookhit;
if (Physics.Raycast (look, out lookhit, 5.0f)) {
Debug.Log ("hi");
Debug.DrawRay (sight.position, sight.forward, Color.red);
navMeshAgent.SetDestination (Player.transform.position);
wandering = false;
}
else
{
wandering = true;
}
}
}
Comment