Scouting AI, need help.

Hey guys.

Fairly new to this, so thanks for the help.

I’m trying to write a simple AI that scouts a random point, then when it gets there, a new destination is set.

For some reason the function I have to set the new position isn’t triggering.
Can anyone spot what I’ve done wrong?
Thanks!

var scoutPosition : Vector3;
var maxScoutX : float = 10;
var maxScoutZ : float = 10;

function Start()
{
	SetNewScoutPos();
}

function SetNewScoutPos()
{
	var position : Vector3 = Vector3(Random.Range(-(maxScoutX), maxScoutX), 0, Random.Range(-(maxScoutZ), maxScoutZ));
		scoutPosition = position;
}

function Update()
{
	GetComponent(NavMeshAgent).destination = scoutPosition;
	
	if (transform.position == scoutPosition)
	{
		SetNewScoutPos();
	}
}

A Vector3 is comprised of 3 floats. Floats represent very specific, fine-grained numbers that sometimes don’t evaluate as expected when checked for equality. Various game systems that work with floats will not always achieve perfect outcomes. If you’re seeing correct movement toward the chosen position, it’s likely that the floating point numbers aren’t an exact match for your equality check. As a general rule, don’t rely on equality checks with floats when using black-boxes like a nav system or even more than simple math, unless you really know what you’re doing.

Typically, in this sort of AI pattern, you would instead use a small trigger area to receive the scout (perhaps even with a timeout). The trigger area accounts for nuances in the pathfinder that might not get the actor to the position to the Nth degree of floating point precision. (The timeout could account for things such as dynamic obstacles.) This way, you can have a callback inform the AI to move to the next position.

You might find it useful to watch transform.position and scoutPosition in the debugger or send them Debug.Log() to see exactly what’s going on. I haven’t worked with this engine’s pathfinder, but I think it will decide “good enough” after achieving a near, but perhaps not exact float equality position.

Good luck!

Worked it out.
Turns out when I hit play, the Y axis was off by a little.

So I changed the IF statement to only look at X and Z.

var scoutPosition : Vector3;
var maxScoutX : float = 10;
var maxScoutZ : float = 10;

function Start()
{
	SetNewScoutPos();
}

function SetNewScoutPos()
{
	var position : Vector3 = Vector3(Random.Range(-(maxScoutX), maxScoutX), 0, Random.Range(-(maxScoutZ), maxScoutZ));
		scoutPosition = position;
}

function Update()
{
	GetComponent(NavMeshAgent).destination = scoutPosition;
	
	if (transform.position.x == scoutPosition.x || transform.position.z == scoutPosition.z)
	{
		SetNewScoutPos();
	}
}