I'm working in Unity3d 2019.2.0f1 and I'm trying to make a chasing bot that follows a certain GameObject
with the "Player" tag.
I'm not yet attempting a field of view approach.
How the Script works:
Step 1 : Overlap a sphere on the Bot AI's transform.position
and put all the things in the sphere inside a Collider[]
.
Step 2: Go through each collider
in ColliderArray and look for a GameObject
with the tag "Player".
Step 3: If found shoot a Raycast
to said GameObject
with tag.
Step 4: If the Gameobject hit does not have the "Player" tag, then the "Player" is being blocked by a obstacle therefor not in the line of sight,
if the GameObject
isn't blocked by an obstacle then we set the destination of the referenced Navmeshagent
.
The problem I'm finding (with about 3000 Debug.Logs) is that the Raycast
only shoots around 7 times and then just stops, also the "Player" needs to stand in a very specific random location (even tho the "Player" is in plane sight).
What am I doing wrong here?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class EnemyAI : MonoBehaviour
{
NavMeshAgent agent;
public float LookRadius = 20; //unity units
void Start()
{
agent = GetComponent<NavMeshAgent>();
}
// Update is called once per frame
void Update()
{
Collider[] colliders = Physics.OverlapSphere(transform.position, LookRadius);
foreach(Collider Object in colliders)
{
if(Object.transform.CompareTag("Player"))
{
RaycastHit hit;
if(Physics.Raycast(transform.position, Object.transform.position, out hit, Vector3.Distance(transform.position, Object.transform.position)))
{
//if not true the we hit a obstacle.
if(hit.transform.CompareTag("Player"))
{
agent.SetDestination(hit.transform.position);
}
}
}
}
}
}