Search Unity

Exponential Moving Average of Quaternions

Discussion in 'Physics' started by twoski, Nov 29, 2014.

  1. twoski

    twoski

    Joined:
    Mar 27, 2014
    Posts:
    27
    Let's say i have a function that finds the exponential moving average of 2 given quaternions.

    I convert them to euler angles to make it easier to do maths with them.

    Example:
    Angle 1 is 0, 0, 10
    Angle 2 is 0, 0, 350

    If we just do (emaAlpha * Angle1 + ((1f - emaAlpha) * Angle2)) where emaAlpha is 0.2, we see that it results in the wrong angle. We want to go from 10 to 350 which is only a difference of 20 degrees, so we want to subtract from 10, not add to it.

    So i have been working on a function which properly handles this, however it doesn't seem to properly work.

    Code (csharp):
    1.  
    2. Vector3 AvgPos(Vector3 lastPos, Vector3 pos) //imagine pos is angle 1, lastPos is angle2
    3.     {
    4.         Vector3 init = (emaAlpha * pos + ((1f - emaAlpha) * lastPos)); //exponential moving average
    5.  
    6.         if (init == pos)
    7.         {
    8.             return init;
    9.         }
    10.  
    11.         Vector3 res = init;
    12.         Vector3 delta = pos - init;
    13.  
    14.         if (Mathf.Abs(pos.x - lastPos.x) > 180f)
    15.         {
    16.             res.x = pos.x - delta.x;
    17.         }
    18.  
    19.         if (Mathf.Abs(pos.y - lastPos.y) > 180f)
    20.         {
    21.             res.y = pos.y - delta.y;
    22.         }
    23.  
    24.         if (Mathf.Abs(pos.z - lastPos.z) > 180f)
    25.         {
    26.             res.z = pos.z - delta.z;
    27.         }
    28.  
    29.         res.x = res.x % 360f;
    30.         res.y = res.y % 360f;
    31.         res.z = res.z % 360f;
    32.  
    33.         return res;
    34.     }
    35.  
    Something is off, it makes my stuff rotate in the wrong direction. Any ideas?