Unity 2D AI agent Z coordinate changes unexpectedly with A* pathfinding system

I’m building a 2D Unity game using the A* pathfinding system. The pathfinding works great - my AI characters find routes correctly and dodge obstacles like they should.

But there’s a weird problem with the Z position. My AI character starts at Z=0 and should move to a target that’s also at Z=0. However, while moving along the path, the character’s Z coordinate keeps changing randomly between values like -8 and -2.

I checked the waypoints on the path and they all show Z=0 like they should. The character prefab also has transform position set to (0,0,0) initially.

I followed the setup guide exactly for 2D games and didn’t change any of the package code. Has anyone seen this Z position drift before? What might cause the AI agent to move away from Z=0 during pathfinding in a 2D project?

Your agent’s treating the game as 3D when you want 2D movement.

Had this exact issue last year on a tower defense prototype. The AI kept drifting on the Z axis while navigating.

Check your AI agent settings for a constraint option that locks Z movement. Most pathfinding systems have “constrain to plane” or something similar.

If that doesn’t help, force it in your movement script:

transform.position = new Vector3(transform.position.x, transform.position.y, 0f);

Drop that at the end of your movement update - it’ll snap Z back to zero every frame. Not the prettiest fix but works great for 2D games.

The waypoints showing Z=0 is normal. The drift happens during movement interpolation between points.

This sounds like a Rigidbody issue, not pathfinding. I had the same Z-axis drift problem - turned out my AI character was using Rigidbody instead of Rigidbody2D. Switch any Rigidbody components on your AI agent to Rigidbody2D and use Collider2D too. The 3D physics system applies forces on all three axes, which causes that random Z movement. Also check your pathfinding agent settings. Some have a ‘Movement Plane’ property - set it to XY for 2D games, not XZ. I missed that once and spent hours debugging floating characters. Your waypoints being correct just confirms pathfinding calculations work fine - it’s the movement execution that’s broken.