Last active
June 14, 2019 19:42
-
-
Save daliborgogic/85bf5933f9eee549b2ae669359a5e506 to your computer and use it in GitHub Desktop.
[devicemoution] Listen to motion events and update the position
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default { | |
mounted () { | |
if (window.DeviceMotionEvent) { | |
// Listen to motion events and update the position | |
window.addEventListener('devicemotion', this.devicemotion, false) | |
} | |
}, | |
destroyed () { | |
window.removeEventListener('devicemotion', this.devicemotion) | |
}, | |
methods: { | |
// Shake sensitivity (a lower number is more) | |
devicemotion (event, sensitivity = 20, delay = 150) { | |
// Position variables | |
let x1 = 0 | |
let y1 = 0 | |
let z1 = 0 | |
let x2 = 0 | |
let y2 = 0 | |
let z2 = 0 | |
const { x, y, z } = event.accelerationIncludingGravity | |
x1 = x | |
y1 = y | |
z1 = z | |
// Periodically check the position and fire | |
// if the change is greater than the sensitivity | |
const that = this | |
setInterval(() => { | |
const change = Math.abs(x1 - x2 + y1 - y2 + z1 - z2) | |
if (change > sensitivity) that.reset() | |
// Update new position | |
x2 = x1 | |
y2 = y1 | |
z2 = z1 | |
}, delay) | |
}, | |
reset () {} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment