Modifying the Relative Orientations of Two Cubes

In the project I’m currently working on, I have 2 cubes. Once a button is pressed by the user I want one of the cubes’ rotation to be rounded to the nearest 90 degrees on every axis relative to the other cube. Is there any way to do this? Thanks!

This should do what you want:

private static Vector3 AxisAlign(Vector3 aVec)
{
    var size = new Vector3(Mathf.Abs(aVec.x), Mathf.Abs(aVec.y), Mathf.Abs(aVec.z));
    if (size.x > size.y)
    {
        if (size.x > size.z)
            return Vector3.right * Mathf.Sign(aVec.x);
    }
    else if (size.y > size.z)
        return Vector3.up * Mathf.Sign(aVec.y);
    return Vector3.forward * Mathf.Sign(aVec.z);
}

public static void AxisAlignTransform(Transform aTrans, Transform aReference)
{
    Vector3 f = AxisAlign(aReference.InverseTransformDirection(aTrans.forward));
    Vector3 u = AxisAlign(aReference.InverseTransformDirection(aTrans.up));
    f = aReference.TransformDirection(f);
    u = aReference.TransformDirection(u);
    aTrans.rotation = Quaternion.LookRotation(f,u);
}

Just call AxisAlignTransform and pass your cube you want to align as first parameter and the reference object as second parameter.

The trick here is to simply convert the target cube’s forward and up vector into the local space of the reference transform. Now they are local vectors and we just need to find the largest value of the 3 vector components as that’s the major direction and will be the closest direction we want.

Once axisaligned we just convert the local vectors back into worldspace where we can use them in LookRotation to calculate the new orientation.