Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 orientation axes jump

I'm making a web app for which I need to know the orientation of the phone around the depth axis: like where the phone would be if it were rotated like the arms on the face of clock. The beta axis tells me this.

However, when I hold the phone in portrait mode facing me, when I tilt the phone back and forth (the way the top card on a Rolodex would be tilted), all the values jump. See video:

https://drive.google.com/file/d/0B5C3MHv2Hmc6VTI2RDlOSkJPVHc/view?usp=sharing

I've tried it on two phones and they are consistent. How can I get that beta axis value without the jumping? I'm sure there is a mathematical way to cancel out the jumps, but I'm not sure where to start.

like image 544
eje211 Avatar asked Apr 25 '17 17:04

eje211


1 Answers

I was about to give up and I thought, "Gee, I never have that kind of problem with Unity. But, of course, Unity has quaternions." This thought led me to think that there must be a Quaternion library for JavaScript and indeed there is.

This led me to this code: I just rotate "up" to the phone orientation converted to a quaternion and grab the z axis:

let quaternion = new Quaternion();
let radian = Math.PI / 180;

$(window).on('deviceorientation', function(event) {
    event = event.originalEvent;
    quaternion.setFromEuler(
        event.alpha * radian,
        event.beta * radian,
        event.gamma * radian);
    let vector3 = quaternion.rotateVector([0, 1, 0]);
    let result = vector3[2];
});

This gives exactly the result I need!

like image 88
eje211 Avatar answered Oct 07 '22 13:10

eje211