Hi guys, just been messing with this AI and enjoying.
Got a bit stuck, I’ve created a simple bot that follows a player ship if it comes in to range but when it’s left that range will go back to a default area. This works fine but I’m now trying to use a snippet of code from the documentation for wondering “https://www.arongranberg.com/astar/docs/wander.html”.
I have used this code on it’s own and work great, but what I’m trying to do is when the player ship is out of range then the bot should head back to the default area and when within a certain distance to start wandering around a specified radius from the default area until the player ship comes back in to range.
I keep getting StackOverflowException. Can someone point me in the right way please.
The code is a bit hack n slash but just trying it out. It’s firstly checking is the player is in range which is highest priority so just heads that direction if the distance is less than the following range.
If it’s out of the range it should head to the default position (protectArea) if this has been defined until it gets within a distance of 100 then if a wonderRadius has been set then should kick in to wondering about.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Pathfinding
{
[UniqueComponent(tag = “ai.destination”)]
[HelpURL(“http://arongranberg.com/astar/docs/class_pathfinding_1_1_a_i_destination_setter.php”)]
public class EnemyContoller : VersionedMonoBehaviour
{
public Transform[] targets;
public float followRange;
public Transform protectArea;
public float wonderRadius;
[HideInInspector]
public Transform target;
IAstarAI ai;
Vector3 PickRandomPoint()
{
var point = Random.insideUnitSphere * wonderRadius;
point.y = 0;
point += ai.position;
return point;
}
void OnEnable()
{
ai = GetComponent<IAstarAI>();
if (ai != null) ai.onSearchPath += Update;
}
void OnDisable()
{
if (ai != null) ai.onSearchPath -= Update;
}
void Update()
{
float distance = 0.0f;
int currentTarget = 0;
float closest = (targets[0].position - transform.position).magnitude;
for (int i = 0; i < targets.Length; i++)
{
distance = (targets[i].position - transform.position).magnitude;
if (distance < closest)
{
closest = distance;
currentTarget = i;
target = targets[currentTarget];
}
}
if (distance < followRange)
{
if (target != null && ai != null)
{
ai.destination = target.position;
}
}
else if (protectArea != null && (protectArea.position - transform.position).magnitude > 100)
if (!ai.pathPending && (ai.reachedEndOfPath || !ai.hasPath))
{
ai.destination = protectArea.position;
}
else if (wonderRadius > 0)
{
ai.destination = PickRandomPoint();
ai.SearchPath();
}
}
}
}