From 0bc844d6c53f2baf49988020843f6768d2351208 Mon Sep 17 00:00:00 2001 From: Rune Harlyk Date: Tue, 25 Jun 2024 21:18:23 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=AA=B0=20Adds=20orientation=20store?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/src/lib/stores/orientation.ts | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 app/src/lib/stores/orientation.ts diff --git a/app/src/lib/stores/orientation.ts b/app/src/lib/stores/orientation.ts new file mode 100644 index 0000000..d3814eb --- /dev/null +++ b/app/src/lib/stores/orientation.ts @@ -0,0 +1,27 @@ +import { readable } from 'svelte/store'; + +export const heading = readable(0, (set) => { + const updateHeading = (e: any) => { + let alpha; + if (e.webkitCompassHeading) alpha = e.webkitCompassHeading; + else if (e.alpha) alpha = e.alpha; + else { + let q = e.target.quaternion; + alpha = + Math.atan2(2 * q[0] * q[1] + 2 * q[2] * q[3], 1 - 2 * q[1] * q[1] - 2 * q[2] * q[2]) * + (180 / Math.PI); + if (alpha < 0) alpha += 360; + } + set(alpha); + }; + if ('AbsoluteOrientationSensor' in window) { + var sensor = new window.AbsoluteOrientationSensor({ frequency: 60 }) as any; + sensor.addEventListener('reading', updateHeading); + sensor.start(); + } else if (window.DeviceMotionEvent) window.addEventListener('deviceorientation', updateHeading); + + return () => { + if ('AbsoluteOrientationSensor' in window) sensor.removeEventListener('reading', updateHeading); + window.addEventListener('deviceorientation', updateHeading); + }; +});