Laya 陀螺仪
1. 先进行判断,如果支持陀螺仪,就进行监测 ```c this.isHaveTuoLuoYi = false; console.log("**** 开始判断是否有陀螺仪 "); if (Laya.Browser.onPC) { this.isHaveTuoLuoYi = false; this.isSendDeviceorientation = false; console.log("**** 电脑端,无陀螺仪 "); } else { if (!SensorHandler.hasPermissions()) { this.isHaveTuoLuoYi = false; console.log("**** 没有授权 "); } else { this.isHaveTuoLuoYi = true; console.log("**** 授权有陀螺仪 "); //判断是否已经发送了协议 if (!this.isSendDeviceorientation) { Laya.Gyroscope.instance.on(Laya.Event.CHANGE, this, this.onDeviceorientation); //Laya.Browser.window.conch.setScreenWakeLock(true); this.isSendDeviceorientation = true; console.log("**** 开始检测陀螺仪变化 "); } } } SensorHandler.ts
declare class SensorHandler { // 请求设备传感器权限 static requestPermissions(): Promise<boolean>; // 检查是否已获得权限(需要用户点击获取,自动调用无效) static hasPermissions(): Promise<boolean>; } sensorHandler.js,将该库放置好,然后在index.js进行添加引用
一定要引用: loadLib(“libs/laya.device.js”),若是在laya2.0里,也要进行勾选这个
loadLib("libs/sensorHandler.js") class SensorHandler { // 请求设备传感器权限 static requestPermissions() { if (window['DeviceMotionEvent'] && typeof DeviceMotionEvent.requestPermission === 'function' && typeof DeviceOrientationEvent.requestPermission === 'function') { return Promise.all([ DeviceOrientationEvent.requestPermission(), DeviceMotionEvent.requestPermission() ]).then((results) => { return results[0] === 'granted' && results[1] === 'granted'; }).catch((err) => { console.error('请求权限时出错:', err); return false; }); } else { console.warn('设备或浏览器不支持权限请求'); return Promise.resolve(false); } } // 检查是否已获得权限 static hasPermissions() { return new Promise((resolve) => { if (window['DeviceMotionEvent'] && typeof DeviceMotionEvent.requestPermission === 'function' && typeof DeviceOrientationEvent.requestPermission === 'function') { resolve(false); // 在 iOS 上无法直接检查权限状态 } else { // 对于不需要请求权限的设备,直接返回 true resolve(true); } }); } } // 暴露类到全局作用域 window.SensorHandler = SensorHandler; 由于不知道什么原因,在index.js引用没有执行,所以在index.html里面又进行了一次引用
在“body /body”里进行添加
<body> <script type="text/javascript"> window.screenOrientation = "landscape"; //window.screenOrientation = "sensor_landscape"; //-----libs-begin----- loadLib("libs/laya.core.js") loadLib("libs/spine-core-4.0.js") loadLib("libs/laya.spine.js") loadLib("libs/laya.ani.js") loadLib("libs/laya.html.js") loadLib("libs/laya.ui.js") loadLib("libs/laya.device.js") loadLib("libs/fairygui.js") loadLib("libs/rawinflate.min.js") loadLib("libs/sensorHandler.js") //-----libs-end------- loadLib("js/bundle.js"); </script> </body>