I have some code to manage to rotation of my Navmesh agents:

if (Agent.isActiveAndEnabled && Agent.hasPath)
            if (Agent.velocity.sqrMagnitude > Mathf.Epsilon)
                transform.rotation = Quaternion.LookRotation(Agent.velocity.normalized);

It's causing my some issues with some odd rotations on the x/z axis for 1-2 frames every now and then, is there some way I can get this exact behaviour but only modify the y-axis?

  • \$\begingroup\$ I've tried this and most other common solutions I can find, in the end the only thing that worked was this: Quaternion tempRot = transform.rotation = Quaternion.LookRotation(Agent.velocity.normalized); tempRot.x = 0; tempRot.z = 0; transform.rotation = tempRot; \$\endgroup\$ – Majs Jan 11 at 11:01

If your agents are always oriented vertically, this is reasonably straightforward. Just project your velocity into the horizontal plane, and look toward that. This can always be accomplished with a pure yaw, no pitch/roll required:

var projected = Agent.velocity;
projected.y = 0f;

if(!Mathf.Approximately(projected.sqrMagnitude, 0f))    
    transform.rotation = Quaternion.LookRotation(projected);

The if check just declines to rotate if the agent has stopped or is travelling purely vertically, which helps avoid a sudden snap to 0-degrees in those cases. Instead, we'll just keep our current yaw.

If your agent can be aligned arbitrarily, then you can use this technique explained in existing answers to locally yaw to face your velocity while keeping your current/desired local up vector fixed.

  • 1
    \$\begingroup\$ This seems to work the same way the code I have in the comment above, but seems a bit nicer. I can prob also replace my Agent.velocity.sqrMagnitude > Mathf.Epsilon check with ur !Mathf.Approximately(projected.sqrMagnitude, 0f) \$\endgroup\$ – Majs Jan 11 at 22:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.