I was about to give up, and I thought: “Gee, I never had such problems with Unity. But, of course, Unity has quaternions.” This thought made me think that for JavaScript there should be a Quaternion library, but there is .
This led me to this code: I just rotate up to the orientation of the phone 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 that I need!
source
share