Sunday 30 June 2019

Device orientation using Quaternion

I've written a JS SDK that listens to mobile device rotation, providing 3 inputs:

α : An angle can range between 0 and 360 degrees
β : An Angle between -180 and 180 degrees
γ : An Angle between -90 to 90 degrees

Documentation for device rotation

I have tried using Euler Angles to determine the device orientation but encountered the gimbal lock effect, that made calculation explode when the device was pointing up. That lead me to use Quaternion, that does not suffer from the gimbal lock effect.

I've found this js library that converts α,β and γ to a Quaternion, so for the following values:

α : 81.7324
β : 74.8036
γ : -84.3221

I get this Quaternion for ZXY order:

w: 0.7120695154301472
x: 0.6893688637611577
y: -0.10864439143062626
z: 0.07696733776346154

Code:

var rad = Math.PI / 180;
window.addEventListener("deviceorientation", function(ev) {

  // Update the rotation object
  var q = Quaternion.fromEuler(ev.alpha * rad, ev.beta * rad, ev.gamma * rad, 'ZXY');

  // Set the CSS style to the element you want to rotate
  elm.style.transform = "matrix3d(" + q.conjugate().toMatrix4() + ")";

}, true);


Visualizing the device orientation using 4d CSS matrix derived from the Quaternion Reflected the right device orientation (DEMO, use mobile):
enter image description here


Wrong visualizing with Euler Angels and the developer tools (DEMO, use mobile):
enter image description here


I would like to write a method that gets α,β and γ and outputs if the device is in one of the following orientations:

  • portrait
  • portrait upside down
  • landscape left
  • landscape right
  • display up
  • display down

Defining each orientation as a range of +- 45° around the relevant axes.

What approach should I take?



from Device orientation using Quaternion

No comments:

Post a Comment