egret.DeviceRotationRate 範例, 官方 egret.Motion 功能已過時
class Main extends eui.UILayer {
protected createChildren(): void {
super.createChildren();
egret.lifecycle.onPause = () => egret.ticker.pause();
egret.lifecycle.onResume = () => egret.ticker.resume();
egret.registerImplementation('eui.IAssetAdapter', new AssetAdapter());
egret.registerImplementation('eui.IThemeAdapter', new ThemeAdapter());
this.runGame();
}
private async loadResource() {
let loadingView = this.stage.addChild(new LoadingUI()) as LoadingUI;
await RES.loadConfig('resource/default.res.json', 'resource/');
await new Promise(resolve => new eui.Theme('resource/default.thm.json', this.stage).once(eui.UIEvent.COMPLETE, resolve, this));
await RES.loadGroup('preload', 0, loadingView);
this.stage.removeChild(loadingView);
}
private async runGame() {
await this.loadResource();
// --- Edwin 給你最乾淨的程式碼, 從這行以下開始寫喔 ---
// 1. https 模式下才有 DeviceMotionEvent, http 不行
// 2. 必須使用者點選按鈕後才能執行 DeviceOrientationEvent.requestPermission
// 3. ios safari 測試有 DeviceOrientationEvent.requestPermission 函式,執行後會跳出 Dialog 詢問是否允許開啟功能,選允許
// 4. 最後記得註冊 devicemotion 事件即可正常執行
// 顯示資訊按鈕
const displayLabel = new eui.Label;
displayLabel.x = 50;
displayLabel.y = 100;
this.addChild(displayLabel);
// 綁定 DeviceMotion 事件按鈕
const triggerBtn = new eui.Button();
triggerBtn.label = '點擊綁定 DeviceMotion 事件';
triggerBtn.y = 50;
triggerBtn.x = 50;
this.addChild(triggerBtn);
triggerBtn.once(egret.TouchEvent.TOUCH_TAP, () => {
// 檢查是否有 requestPermission 功能
if (typeof DeviceMotionEvent['requestPermission'] === 'function') {
// 詢問是否可以啟用 devicemotion 功能
DeviceMotionEvent['requestPermission']()
.then(response => {
if (response == 'granted') {
// 註冊 devicemotion 事件
window.addEventListener('devicemotion', e => {
const acceleration:egret.DeviceAcceleration = {
x: e.acceleration.x,
y: e.acceleration.y,
z: e.acceleration.z
};
const accelerationIncludingGravity:egret.DeviceAcceleration = {
x: e.accelerationIncludingGravity.x,
y: e.accelerationIncludingGravity.y,
z: e.accelerationIncludingGravity.z
};
const rotation:egret.DeviceRotationRate = {
alpha: e.rotationRate.alpha,
beta: e.rotationRate.beta,
gamma: e.rotationRate.gamma
};
const event = { acceleration, accelerationIncludingGravity, rotation };
displayLabel.text = JSON.stringify(event, null, '\t');
});
}
})
.catch(function (error) {
displayLabel.text = 'DeviceMotionEvent not enabled : '+error;
})
} else {
displayLabel.text = 'DeviceMotionEvent not support!';
}
}, this);
}
}
沒有留言:
張貼留言