Please help me, how to use an Accelerometer to shake it
I want to achieve that when I shake my phone, the data increases and vibrates continuously. The data will continue to increase and vibrate continuously
Here is the code I am currently using. Although it responds when shaken, it is not smooth
if (window.Telegram?.WebApp?.Accelerometer) {
window.Telegram.WebApp.Accelerometer
.start({
frequency: 90
}, (started) => {
if (started) {
console.log('ok');
this.checkAccelerometer();
} else {
console.log('no');
}
});
}
checkAccelerometer() {
if (!window.Telegram?.WebApp?.Accelerometer?.isStarted) {
this.isShaking = false;
return;
}
const currentTime = new Date().getTime();
const x = window.Telegram.WebApp.Accelerometer.x;
const y = window.Telegram.WebApp.Accelerometer.y;
const z = window.Telegram.WebApp.Accelerometer.z;
if ((currentTime - this.lastUpdate) > this.timeThreshold) {
const diffTime = currentTime - this.lastUpdate;
const diffX = this.lastX - x;
const diffY = this.lastY - y;
const diffZ = this.lastZ - z;
const speed = Math.sqrt(diffX * diffX + diffY * diffY + diffZ * diffZ) / diffTime * 10000;
if (speed < this.minThreshold) {
if (this.isShaking) {
this.isShaking = false;
console.log('stop');
}
} else if (speed > this.shakeThreshold &&
currentTime - this.lastShakeTime > this.shakeCooldown) {
this.onShake();
this.lastShakeTime = currentTime;
}
this.lastUpdate = currentTime;
this.lastX = x;
this.lastY = y;
this.lastZ = z;
}
requestAnimationFrame(this.checkAccelerometer);
},
New contributor
Andrew is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1