Smooth alignments using quaternion interpolation

Originally posted in a different thread: Original Comment

Example file for UPBGE 0.2.5, but code is simple and should be copy-able to any version
rotateQuatExample.blend (725.7 KB)

The Python API has a function, called alignAxisToVect(), which allows you to align any object (usually your game’s character) to a given Vector.
This is often used to make your character point a certain way, or to make enemy AI automatically track the player or something else.

However, this function is a little bit wacky (even though it functions mostly as intended). Often it gives jittery results, or your character suddenly flips, or other events happen because of Euler orientations. An euler orientations is a set of 3 angles you can use to describe any 3D orientation, but when you try to rotate an object it runs into a problem called gimbal lock. More information here: https://en.wikipedia.org/wiki/Gimbal_lock

Of course, there is a solution - Quaternions! Quaternions use 4 dimensions to avoid the problem altogether, but they are a bit difficult to understand and use. Fortunately, BGE (and Blender’s mathutils) has an easy API to use them, and interpolate between vectors using quaternion linear interpolation (spherical lerp, AKA slerp())

It may still be a bit confusing, but the example file at the beginning of this post shows you how to use it (and encapsulates it in a function).

Video I posted a while back on the UPBGE discord of the file. The cool thing is that you don’t need any “up axis”, like in the “Track To” logic brick. I believe RanGE also has a new “Look At” node that should function better than Track To