Skip to content

Instantly share code, notes, and snippets.

@daliborgogic
Last active June 14, 2019 19:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daliborgogic/85bf5933f9eee549b2ae669359a5e506 to your computer and use it in GitHub Desktop.
Save daliborgogic/85bf5933f9eee549b2ae669359a5e506 to your computer and use it in GitHub Desktop.
[devicemoution] Listen to motion events and update the position
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