Sel
Sel

Reputation: 352

Converting gyroscope values consistently across Android and iOS with Matter.js

I am using the Matter gyro demo in my project and it works perfectly on Android. However, I'm not able to achieve consistent results on iOS.

This is the relevant snippet I have taken from the gyro demo:

if (window.screen.orientation.angle === 0) {
  engine.gravity.x = Common.clamp(event.gamma, -90, 90) / 90
  engine.gravity.y = Common.clamp(event.beta, -90, 90) / 90
} else if (window.screen.orientation.angle === 90) {
  engine.gravity.x = Common.clamp(event.beta, -90, 90) / 90
  engine.gravity.y = Common.clamp(-event.gamma, -90, 90) / 90
} else if (window.screen.orientation.angle === 180) {
  engine.gravity.x = Common.clamp(event.gamma, -90, 90) / 90
  engine.gravity.y = Common.clamp(-event.beta, -90, 90) / 90
} else if (window.screen.orientation.angle === -90) {
  engine.gravity.x = Common.clamp(-event.beta, -90, 90) / 90
  engine.gravity.y = Common.clamp(event.gamma, -90, 90) / 90
}

However, if I run this on my iPad Air (5th gen) running iOS 17.4.1 the gravity pulls to the right instead of down. I thought I could sniff the browser and write an alternative beta / gamma to x / y conversion, which I did and it looks like this:

if (window.screen.orientation.angle === 0) {
  engine.gravity.x = Common.clamp(event.beta, -90, 90) / 90
  engine.gravity.y = Common.clamp(-event.gamma, -90, 90) / 90
} else if (window.screen.orientation.angle === 90) {
  engine.gravity.x = Common.clamp(event.gamma, -90, 90) / 90
  engine.gravity.y = Common.clamp(event.beta, -90, 90) / 90
} else if (window.screen.orientation.angle === 180) {
  engine.gravity.x = Common.clamp(-event.beta, -90, 90) / 90
  engine.gravity.y = Common.clamp(event.gamma, -90, 90) / 90
} else if (window.screen.orientation.angle === 270) {
  engine.gravity.x = Common.clamp(-event.gamma, -90, 90) / 90
  engine.gravity.y = Common.clamp(-event.beta, -90, 90) / 90
}

However, when my client tested the above on their iPad Pro (3rd gen) running iOS 16.4.1 gravity pulled to the right again, even though on my iPad it pulled down.

I ended up writing a little tool that let me observe the readings of beta / gamma, and I can confirm the readings are different on iOS when compared to Android. I also stumbled across this library called Full Tilt which appeared to address the issue, but I cannot use as it has since fallen out of maintenance (I am building with webpack).

Has anyone had any luck with the gyro and getting it to work consistently across Android and iOS devices?

Upvotes: 0

Views: 58

Answers (0)

Related Questions