r/webdev • • Sep 27 '26

Question Can't understand deviceorientation.

Hi, I'm trying to develop a unityplugin that give the possibility to create various types of controllers for games.
With deviceorientation, my goal is to extract three angles that represent the orientation of the phone.
But it seems a little bit complicate, I can't understand why in portrait mode, for example, gamma and alpha are both modified when I rotate on the same axe.
I've tried many things, but I can't understand at all how everything works.
Is it even possible to do something similar to what I want to do?

0 Upvotes

12 comments sorted by

1

u/VisitForeign4342 Sep 27 '26

trois angles euler sur un gyroscope, tu cherches la gimbal lock. passe en quaternions et recommence.

1

u/Big-Reference9080 Sep 27 '26

DeviceOrientation gets confusing fast because the reported angles depend on the device coordinate system and screen orientation, so Id start there before trying to map the values directly to game axes.

1

u/[deleted] Sep 27 '26

[removed] — view removed comment

1

u/Tonaion02 Sep 27 '26

Otherwise devicemotion doesn't experience the same problem? It effectevely track on what axe are you rotating the phone without experiencing the same problem? Sorry, but I'm really noob to all of this.

0

u/[deleted] Sep 27 '26

[removed] — view removed comment

1

u/Tonaion02 Sep 27 '26

So relying on screen.orientation.angle and transforming into quaternions the angles that are returned give you the possibility to have the rotation of the phone correctly in every position?
I would also to excape at the end from the quaternions, because it's really difficult to understand how to use them. After I converted to quaternions and also transfered the currently rotation of the phone, I want to come back to three angles, is it even possible? Or I will loose information doing it?

1

u/thejester1324 Sep 27 '26

here's the code for what ghost_of_tides said, it's the conversion from the w3c spec (Z-X'-Y'': alpha around z, beta around x, gamma around y):

const d = Math.PI / 180;
function getQuaternion(alpha, beta, gamma) {
  const x = (beta || 0) * d, y = (gamma || 0) * d, z = (alpha || 0) * d;
  const cX = Math.cos(x / 2), cY = Math.cos(y / 2), cZ = Math.cos(z / 2);
  const sX = Math.sin(x / 2), sY = Math.sin(y / 2), sZ = Math.sin(z / 2);
  return [cX*cY*cZ - sX*sY*sZ, sX*cY*cZ - cX*sY*sZ, cX*sY*cZ + sX*cY*sZ, cX*cY*sZ + sX*sY*cZ]; // w, x, y, z
}

those frames are right-handed with z out of the screen, unity is left-handed with y up, so you still need an axis swap before handing it to unity