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:
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With