How does AIBase.Move() work?

Hey, I’m trying to get AIBase.Move(Vector3 deltaPosition) to work

In my case I’m trying to implement evasive movement in 2D (the enemy weaves side to side while approaching the player, like a zig zag along the path to the player)

My code is like this in the Enemy’s Update:

Vector2 moveDir = GetComponent<IAstarAI>().velocity;
Vector2 perpendicularMovement = Vector2.Perpendicular(moveDir) * Mathf.Sin(Time.time);
GetComponent<AIPath>().Move(perpendicularMovement * Time.deltaTime);

As you can see from the code I’m trying to add movement perpendicular to the Enemy’s velocity and sine-ing the movement to give back and forth, but this gives very erratic movement (the enemy “vibrates” around and then teleports erraticly a bit)

I’ve tried using FinalizeMovement() in conjunction with this but no luck, are there any examples for this or am I doing something wrong?



You probably don’t want to include the ai’s own velocity in your calculations, since your Move call will affect that velocity. This probably leads to weird effects when run every frame like that. You could use ai.steeringTarget instead, that might work better.

1 Like

Thanks got this working and that’s a good point, calling Move() increases velocity so running this code increases the velocity exponentially, also don’t know why I wasn’t normalising it in the first place.

Another thing I didn’t take into account is making sure that IAstarAI.canMove is true, since calling Move() when it’s false increases accumulatedMovementDelta until canMove is true, leading to accumulatedMovementDelta being added all at once leading to teleports.

Here’s my working code for anybody who will find this helpful:

void Awake()
	_iAStarAI = GetComponent<IAstarAI>();
	_aiPath = GetComponent<AIPath>();

void Update()
	if (_iAStarAI.canMove)
		Vector2 moveDir = _iAStarAI.steeringTarget;
		Vector2 perpDir = Vector2.Perpendicular(moveDir).normalized;

		// Zig Zag evasive movement
		_aiPath.Move(((int)(Time.time * 5f) % 2 == 0 ? perpDir : -perpDir) * Time.deltaTime * 2);

		// Sine Wave evasive movement
		// _aiPath.Move(perpDir * 2f * Mathf.Sin(10 * Time.time) * Time.deltaTime);

Commented out a sine wave movement variation, should be easy enough to add randomness into the zig zag movement

Is there a way to mark the question as solved? Can’t see any :sweat_smile: