how do I snap vector to the nearest "cardinal" value.

let's say I have an object that can rotate any way and direction, by any amount. at times though we'd need to take the object's transform.up and check: if it was "rounded up" (or down, wherever it would be closer) to the closest "cardinal Vector3" (I mean Vector3.right vector3.up or vector3.forward (or respectively: minus vector3.right/up/ forward)) what would it be.

How could that be done?

Follow these steps:

  1. Check which component of the vector(x, y, or z) has the biggest absolute value.
  2. Make that component 1, and all others 0.
  3. Change the sign to the original sign of that component.

For anyone who wants a Vector3 extension that also supports changing the relative space using this technique.

/// <summary>
/// Rounds a Vector3 to world axis or relative to another transform
/// </summary>
/// <param name="vector">Vector to round</param>
/// <param name="relativeTo">Optional relative transform space axis</param>
/// <returns></returns>
public static Vector3 AxisRound(this Vector3 vector, Transform relativeTo = null)
{
    if (relativeTo)
    {
        vector = relativeTo.InverseTransformDirection(vector);
    }
    int largestIndex = 0;
    for (int i = 1; i < 3; i++)
    {
         largestIndex = Mathf.Abs(vector*) > Mathf.Abs(vector[largestIndex]) ? i : largestIndex;*

}
float newLargest = vector[largestIndex] > 0 ? 1 : -1;
vector = Vector3.zero;
vector[largestIndex] = newLargest;
if (relativeTo)
{
vector = relativeTo.TransformDirection(vector);
}
return vector;
}