Created
September 30, 2016 17:30
-
-
Save samgiles/753641697e14146741fe908844553b2d to your computer and use it in GitHub Desktop.
Simple knock/tap detector
This file contains 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
<html> | |
<body> | |
<script> | |
const state = { | |
x: 0, | |
y: 0, | |
z: 0, | |
knocked: 0, | |
}; | |
const WINDOW_SIZE_MS = 500; | |
const KNOCK_THRESHOLD_MS = 500; | |
let framesPerWindow = 0; | |
let frames = 0; | |
window.ondevicemotion = function(event) { | |
let {x, y, z} = event.acceleration; | |
x = x === NaN ? 0 : x; | |
y = y === NaN ? 0 : y; | |
z = z === NaN ? 0 : z; | |
framesPerWindow = WINDOW_SIZE_MS / event.interval; | |
if (frames < framesPerWindow) { | |
frames++; | |
} | |
state.x = (((frames - 1) * state.x) + x) / frames | |
state.y = (((frames - 1) * state.y) + y) / frames | |
state.z = (((frames - 1) * state.z) + z) / frames | |
if (frames >= framesPerWindow) { | |
if ( | |
x > (state.x + 0.8) || | |
y > (state.y + 0.8) || | |
z > (state.z + 0.8) | |
) { | |
state.knocked++; | |
} | |
if (state.knocked === 1) { | |
state.firstKnock = Date.now(); | |
} | |
if (state.firstKnock) { | |
if ((Date.now() - state.firstKnock) > KNOCK_THRESHOLD_MS) { | |
console.log(state.knocked); | |
if (state.knocked >= 2 && state.knocked < 9) { | |
const pEl = document.createElement('p'); | |
pEl.innerText = "Knocked!"; | |
document.body.appendChild(pEl); | |
} | |
state.knocked = 0; | |
state.firstKnock = false; | |
} | |
} | |
} | |
}; | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment