LookRotation alternative using other custom vectors

I found that Quaternion.LookRotation is rather limited. You can only align the object’s forward and up vector with the input vectors. If you want to align the object with any vectors other then the forward and up vector, this function falls short. I have seen various posts discussing this problem. This function solves that:

//This is an alternative for Quaternion.LookRotation. Instead of aligning the forward and up vector of the game
//object with the input vectors, a custom direction can be used instead of the fixed forward and up vectors.
//destinationVector and destinationNormal are in world space.
//customForward and customUp are in object space.
//Usage: use destinationVector and destinationNormal as if you are using the default LookRotation function.
//Set customForward and customUp to the vectors you wish to use instead of the default forward and up vectors.
void lookRotationExtended(ref GameObject gameObjectInOut, Vector3 destinationVector, Vector3 destinationNormal, Vector3 customForward, Vector3 customUp){
       
    //Set the rotation of the destination
    Quaternion rotationA = Quaternion.LookRotation(destinationVector, destinationNormal);      
       
    //Set the rotation of the custom normal and up vectors.
    //When using the default LookRotation function, this would be hard coded to the forward and up vector.
    Quaternion rotationB = Quaternion.LookRotation(customForward, customUp);
       
    //Calculate the rotation
    gameObjectInOut.transform.rotation =  rotationA * Quaternion.Inverse(rotationB);
}

Unity wiki page:
http://wiki.unity3d.com/index.php/3d_Math_functions

1 Like

Thanks, shoving this in my “Keep” folder