Skip to content

Instantly share code, notes, and snippets.

@thyngster
Created April 12, 2025 03:29
Show Gist options
  • Save thyngster/e1a5b9848cd05706d4436ab0d7f57064 to your computer and use it in GitHub Desktop.
Save thyngster/e1a5b9848cd05706d4436ab0d7f57064 to your computer and use it in GitHub Desktop.
Movement Detector
class MovementDetector {
constructor(options = {}) {
// Configuration with defaults
this.threshold = options.threshold || 5;
this.debug = options.debug || false;
this.onMovementChange = options.onMovementChange || null;
// State tracking
this.lastRotation = { x: 0, y: 0, z: 0 };
this.isMoving = false;
// Bind the handler to preserve 'this' context
this.handleDeviceMotion = this.handleDeviceMotion.bind(this);
}
start() {
window.addEventListener("devicemotion", this.handleDeviceMotion);
if (this.debug) console.log("Movement detector started");
}
stop() {
window.removeEventListener("devicemotion", this.handleDeviceMotion);
if (this.debug) console.log("Movement detector stopped");
}
handleDeviceMotion(event) {
const rotation = {
x: event.rotationRate.alpha,
y: event.rotationRate.beta,
z: event.rotationRate.gamma
};
// Calculate differences on all axes
const diffs = {
x: Math.abs(rotation.x - this.lastRotation.x),
y: Math.abs(rotation.y - this.lastRotation.y),
z: Math.abs(rotation.z - this.lastRotation.z)
};
// Check if any axis exceeds the threshold
const movementDetected =
diffs.x > this.threshold ||
diffs.y > this.threshold ||
diffs.z > this.threshold;
// Only report changes in movement state
if (movementDetected !== this.isMoving) {
this.isMoving = movementDetected;
if (this.debug) {
console.log(this.isMoving ? "Movement detected!" : "Movement stopped");
}
// Call the callback if provided
if (typeof this.onMovementChange === 'function') {
this.onMovementChange(this.isMoving);
}
}
// Update last rotation values
this.lastRotation = rotation;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment