如何解决devicemotion脚本问题?陀螺仪检测代码故障求助
It looks like you're having trouble getting your gyro/DeviceMotion script to work properly. Let's break down common pitfalls and fixes based on the code snippet you shared:
First, Fix the Incomplete Event Handling
Your code cuts off at event.rotationRat... — make sure you're accessing the rotationRate properties correctly. The DeviceMotionEvent gives you alpha, beta, and gamma values through this property. Here's a complete example of the listener:
window.addEventListener("devicemotion", function(event) { console.log("device motion detected!"); if (event.rotationRate) { const { alpha, beta, gamma } = event.rotationRate; // Pass these values to your update function instead of relying on setTimeout alone update_gyro_value(alpha, beta, gamma); } });
Don't Forget Permission Requests
Modern browsers (especially iOS Safari and Chromium-based mobile browsers) require explicit user permission to access motion sensors. You can't just start listening for events anymore — you need to ask first. Here's how to integrate that into your check_user_hardware function:
async function check_user_hardware() { // Assuming mobile_size is checking viewport width if (window.innerWidth <= 600) { hidden = true; } console.log("checking hardware"); // Check if permission is needed if (typeof DeviceOrientationEvent.requestPermission === 'function') { try { const permissionStatus = await DeviceOrientationEvent.requestPermission(); if (permissionStatus === 'granted') { // Only set up listeners and timers if permission is granted window.addEventListener("devicemotion", handleDeviceMotion); // If you still need the timeout, make sure it's dependent on permission giro_timer = setTimeout(update_gyro_value, 30); } else { console.log("User denied permission to access motion sensors"); } } catch (err) { console.error("Error requesting motion sensor permission:", err); } } else { // Older browsers or devices that don't require permission window.addEventListener("devicemotion", handleDeviceMotion); giro_timer = setTimeout(update_gyro_value, 30); } } // Separate handler function for clarity function handleDeviceMotion(event) { console.log("device motion?"); if (event.rotationRate) { update_gyro_value(event.rotationRate.alpha, event.rotationRate.beta, event.rotationRate.gamma); } } // Update your gyro value function to accept parameters function update_gyro_value(alpha, beta, gamma) { // Do something with these values here console.log(`Gyro: Alpha=${alpha}, Beta=${beta}, Gamma=${gamma}`); }
Fix Timing Issues
Your current setTimeout runs update_gyro_value after 30ms, but if the DeviceMotion event hasn't fired yet, you might be trying to access values that don't exist. It's better to trigger updates directly when the event occurs (like in the handleDeviceMotion function above) instead of relying on a timeout alone.
Check Compatibility and HTTPS
- Device/Browser Support: Not all devices or browsers support DeviceMotion. Add a check first:
if (!('DeviceMotionEvent' in window)) { console.log("DeviceMotion is not supported on this device"); return; } - HTTPS Requirement: Most modern browsers block sensor APIs on HTTP sites. Make sure your site is served over HTTPS (localhost is okay for development).
Next Steps to Debug
- Check the Console: Look for errors related to permission denied, undefined properties, or blocked APIs.
- Share Full Code: If you're still stuck, post the complete
update_gyro_valuefunction and the rest of your DeviceMotion listener code. - Test on Real Devices: Sensor APIs usually don't work in desktop emulators — test on an actual mobile device.
内容的提问来源于stack exchange,提问作者FutureCake

