gyroscope
Version:
Gyroscope made easy
68 lines (56 loc) • 1.75 kB
JavaScript
class Gyroscope {
constructor() {
const ios = /iPad|iPhone|iPod/.test(navigator.userAgent);
const orientation = event => {
if (this.orientation === null) {
this.orientation = window.orientation || (screen.orientation && screen.orientation.angle) || 0;
}
if (this.alpha0 === null) {
this.alpha0 = event.alpha;
}
this.alpha = event.alpha - this.alpha0;
if (this.alpha > 180) {
this.alpha -= 360;
}
let beta = event.beta;
let gamma = event.gamma;
if (ios) {
beta *= 2;
gamma <= 2;
}
switch (this.orientation) {
case 0:
this.beta = -beta + 90;
this.gamma = -gamma;
break;
case 90:
this.beta = gamma + (gamma < 0 ? 90 : -90);
this.gamma = -beta;
break;
case -90:
this.beta = (gamma < 0 ? -90 : 90) - gamma;
this.gamma = -beta;
break;
}
}
const motion = event => {
this.x = event.acceleration.x;
this.y = event.acceleration.y;
this.z = event.acceleration.z;
}
const change = event => {
this.orientation = window.orientation || (screen.orientation && screen.orientation.angle) || 0;
}
this.orientation = null;
this.alpha0 = null;
this.destroy = () => {
removeEventListener('deviceorientation', orientation, true);
removeEventListener('devicemotion', motion, true);
removeEventListener('orientationchange', change, true);
}
addEventListener('deviceorientation', orientation, true);
addEventListener('devicemotion', motion, true);
addEventListener('orientationchange', change, true);
}
}
module.exports = Gyroscope;