This script has a problem:
It should change chaseMode
to true
when playerToChase
is colliding with visionCollider
, but that doesn’t happen.
I tried different solutions but nothing works. The objects have the collider components properly set up.
the script:
using System.Collections;
using UnityEngine;
using UnityEngine.AI;
public class AntagonistAI : MonoBehaviour
{
[Header("Configuration")]
public GameObject antagonist;
public GameObject visionCollider;
public GameObject playerToChase;
public float updateSpeed = 1f;
public bool chaseMode = false;
[Header("Walking")]
public float walkSpeed = 10f;
public Transform[] pathPoints;
private int currentPathIndex = 0;
[Header("Chasing")]
public float chaseSpeed = 15f;
public float giveupDistance = 30f;
private NavMeshAgent navMeshAgent;
private void Start()
{
navMeshAgent = antagonist.GetComponent<NavMeshAgent>();
StartCoroutine(UpdateAI());
}
void Update() {
// wtf lol this is cursed
if (playerToChase != null && visionCollider != null && playerToChase.GetComponent<Collider>().bounds.Intersects(visionCollider.GetComponent<Collider>().bounds))
{
// this doesn't work
chaseMode = true;
Debug.log("omg collision works")
}
}
private IEnumerator UpdateAI()
{
while (true)
{
if (!chaseMode)
{
Patrol();
}
else
{
Chase();
}
yield return new WaitForSeconds(updateSpeed);
}
}
private void Patrol()
{
if (pathPoints.Length == 0)
{
Debug.LogError("patrol points not set.");
return;
}
navMeshAgent.speed = walkSpeed;
if (navMeshAgent.remainingDistance < 0.5f)
{
currentPathIndex = (currentPathIndex + 1) % pathPoints.Length;
navMeshAgent.SetDestination(pathPoints[currentPathIndex].position);
Debug.Log("moving to point.");
}
}
private void Chase()
{
if (playerToChase == null)
{
Debug.LogError("player object is bad");
chaseMode = false;
return;
}
navMeshAgent.speed = chaseSpeed;
navMeshAgent.SetDestination(playerToChase.transform.position);
float distanceToPlayer = Vector3.Distance(antagonist.transform.position, playerToChase.transform.position);
if (distanceToPlayer > giveupDistance)
{
chaseMode = false;
Debug.Log("Chasing stopped.");
}
}
}