Refine sensor integration strategy

This commit is contained in:
2026-03-25 17:42:16 +08:00
parent a19342d61f
commit f7d4499e36
11 changed files with 1509 additions and 8 deletions

View File

@@ -0,0 +1,85 @@
export interface GyroscopeControllerCallbacks {
onSample: (x: number, y: number, z: number) => void
onError: (message: string) => void
}
export class GyroscopeController {
callbacks: GyroscopeControllerCallbacks
listening: boolean
starting: boolean
gyroCallback: ((result: WechatMiniprogram.OnGyroscopeChangeCallbackResult) => void) | null
constructor(callbacks: GyroscopeControllerCallbacks) {
this.callbacks = callbacks
this.listening = false
this.starting = false
this.gyroCallback = null
}
start(): void {
if (this.listening || this.starting) {
return
}
if (typeof wx.startGyroscope !== 'function' || typeof wx.onGyroscopeChange !== 'function') {
this.callbacks.onError('当前环境不支持陀螺仪监听')
return
}
const callback = (result: WechatMiniprogram.OnGyroscopeChangeCallbackResult) => {
if (
typeof result.x !== 'number'
|| typeof result.y !== 'number'
|| typeof result.z !== 'number'
|| Number.isNaN(result.x)
|| Number.isNaN(result.y)
|| Number.isNaN(result.z)
) {
return
}
this.callbacks.onSample(result.x, result.y, result.z)
}
this.gyroCallback = callback
wx.onGyroscopeChange(callback)
this.starting = true
wx.startGyroscope({
interval: 'game',
success: () => {
this.starting = false
this.listening = true
},
fail: (res) => {
this.starting = false
this.detachCallback()
this.callbacks.onError(res && res.errMsg ? res.errMsg : 'startGyroscope failed')
},
})
}
stop(): void {
this.detachCallback()
wx.stopGyroscope({
complete: () => {},
})
this.starting = false
this.listening = false
}
destroy(): void {
this.stop()
}
private detachCallback(): void {
if (!this.gyroCallback) {
return
}
if (typeof wx.offGyroscopeChange === 'function') {
wx.offGyroscopeChange(this.gyroCallback)
}
this.gyroCallback = null
}
}