Hi there! I’m working with AI for my 3D RPG and I’m having a small issue with my current setup.
So the AI is a NavMeshAgent and I was making the AI wander to a random location on the NavMesh, but if the player gets within a certain radius, the AI began chasing the player.
Here is that part of my AI code:
private void Update()
{
Follow();
Wander();
}
private void Follow()
{
if (followPlayer)
{
distance = Vector3.Distance(transform.position, player.transform.position);
if (distance <= chaseRadius)
{
agent.SetDestination(player.transform.position);
}
if (distance <= attackRadius)
{
RotateTowards(player.transform);
Attack();
}
if (distance > chaseRadius)
{
if (wander)
{
if (newPos != null)
{
agent.SetDestination(newPos);
}
}
}
}
}
private void Wander()
{
if (wander)
{
if (Vector3.Distance(transform.position, newPos) <= agent.stoppingDistance * 1.2f)
{
positionMarker.GetComponent<MeshRenderer>().material = green;
timer += Time.deltaTime;
if (timer >= waitTimer)
{
Debug.Log("<color=green>Looking for new wander location...</color>");
//newPos = RandomNavSphere(transform.position, wanderRadius, -1);
while (Vector3.Distance(transform.position, newPos) <= agent.stoppingDistance * minDistanceMultiplier)
{
newPos = RandomNavSphere(transform.position, wanderRadius, -1);
}
agent.SetDestination(newPos);
positionMarker.GetComponent<MeshRenderer>().material = red;
positionMarker.transform.position = newPos;
Debug.DrawLine(transform.position, newPos, Color.red, waitTimer);
timer = 0;
}
}
}
}
This was working fine with exterior locations along large terrains, but now I’m testing it out inside of a “dungeon” which is basically a simple 3D maze, and I’ve run into an issue I’m trying to figure out:
The chaseRadius is a sphere, so if the player is in a hallway above or bellow the AI, the AI will start trying to follow the player, which is not what I want. Even worse, the AI can get stuck because it will start following the player, then move in a way that the player is no longer in the radius of that sphere so it will move to a wander location, then start chasing the player again, stuck in a loop.
I think what I want is for a sort of line of sight logic for the AI. I hadn’t really given this much thought before, but it makes more sense anyway. So, the AI would need to be facing the player, and have a clear line of sight to the player (i.e. no objects, walls, or floors in between) before it starts chasing.
I’m sure this is doable, but I honestly don’t know where to start. Any tips or resources would be greatly welcome!!! Thanks so much!