Question by
PaincideStudio · Feb 17, 2018 at 06:45 AM ·
raycastainavmeshchase
AI chase/follow problem
Hi I made a script which AI wanders and when see player, it starts to chase player.
But it never chase the player even though it see the player.
I'm trying to make AI raycasts player.
Here is the script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class BeuBaeMovement : MonoBehaviour {
public GameObject B;
public GameObject Player;
NavMeshAgent navMeshAgent;
NavMeshPath path;
public float timeForNewPath;
bool inCoRoutine;
Vector3 target;
bool validPath;
public Animator anim;
void Start()
{
navMeshAgent = GetComponent<NavMeshAgent> ();
path = new NavMeshPath ();
}
void Update()
{
if (!inCoRoutine)
StartCoroutine (DoSomething ());
if (navMeshAgent.velocity.magnitude > 1.0f)
{
anim.SetBool ("IsWalking", true);
}
else
{
anim.SetBool ("IsWalking", false);
}
Vector3 left15Degs = Quaternion.Euler (0, -15, 0) * transform.forward;
Ray ray = new Ray(B.transform.position, left15Degs);
RaycastHit hit;
if (Physics.Raycast (ray, out hit, 3.0f))
{
if (hit.collider.CompareTag("Player"))
{
navMeshAgent.destination = Player.transform.position;
}
}
}
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);
}
}
Comment