gyroscopeController.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. export interface GyroscopeControllerCallbacks {
  2. onSample: (x: number, y: number, z: number) => void
  3. onError: (message: string) => void
  4. }
  5. export class GyroscopeController {
  6. callbacks: GyroscopeControllerCallbacks
  7. listening: boolean
  8. starting: boolean
  9. gyroCallback: ((result: WechatMiniprogram.OnGyroscopeChangeCallbackResult) => void) | null
  10. constructor(callbacks: GyroscopeControllerCallbacks) {
  11. this.callbacks = callbacks
  12. this.listening = false
  13. this.starting = false
  14. this.gyroCallback = null
  15. }
  16. start(): void {
  17. if (this.listening || this.starting) {
  18. return
  19. }
  20. if (typeof wx.startGyroscope !== 'function' || typeof wx.onGyroscopeChange !== 'function') {
  21. this.callbacks.onError('当前环境不支持陀螺仪监听')
  22. return
  23. }
  24. const callback = (result: WechatMiniprogram.OnGyroscopeChangeCallbackResult) => {
  25. if (
  26. typeof result.x !== 'number'
  27. || typeof result.y !== 'number'
  28. || typeof result.z !== 'number'
  29. || Number.isNaN(result.x)
  30. || Number.isNaN(result.y)
  31. || Number.isNaN(result.z)
  32. ) {
  33. return
  34. }
  35. this.callbacks.onSample(result.x, result.y, result.z)
  36. }
  37. this.gyroCallback = callback
  38. wx.onGyroscopeChange(callback)
  39. this.starting = true
  40. wx.startGyroscope({
  41. interval: 'game',
  42. success: () => {
  43. this.starting = false
  44. this.listening = true
  45. },
  46. fail: (res) => {
  47. this.starting = false
  48. this.detachCallback()
  49. this.callbacks.onError(res && res.errMsg ? res.errMsg : 'startGyroscope failed')
  50. },
  51. })
  52. }
  53. stop(): void {
  54. this.detachCallback()
  55. wx.stopGyroscope({
  56. complete: () => {},
  57. })
  58. this.starting = false
  59. this.listening = false
  60. }
  61. destroy(): void {
  62. this.stop()
  63. }
  64. private detachCallback(): void {
  65. if (!this.gyroCallback) {
  66. return
  67. }
  68. if (typeof wx.offGyroscopeChange === 'function') {
  69. wx.offGyroscopeChange(this.gyroCallback)
  70. }
  71. this.gyroCallback = null
  72. }
  73. }