diff --git a/src/components/cardboard-controls.js b/src/components/cardboard-controls.js index ebfc471671e112715d23c5eef0b1545b6ab562f0..8b4ea1416bc176db9bdfbd7118f29d720b30dc41 100644 --- a/src/components/cardboard-controls.js +++ b/src/components/cardboard-controls.js @@ -1,12 +1,31 @@ -const CARDBOARD_BUTTON = "Cardboard Button"; +const CARDBOARD_BUTTON_GAMEPAD_ID = "Cardboard Button"; module.exports = AFRAME.registerComponent("cardboard-controls", { init: function() { this.buttons = {}; this.gamepad = null; + this.isMobile = AFRAME.utils.device.isMobile(); + this.isVR = false; + + this._handleEnterVR = this._handleEnterVR.bind(this); + this._handleExitVR = this._handleExitVR.bind(this); + }, + + play: function() { + window.addEventListener("enter-vr", this._handleEnterVR); + window.addEventListener("exit-vr", this._handleExitVR); + }, + + pause: function() { + window.removeEventListener("enter-vr", this._handleEnterVR); + window.removeEventListener("exit-vr", this._handleExitVR); }, tick: function() { + if (!this.inVR || !this.isMobile) { + return; + } + this.gamepad = this.gamepad || this._getGamepad(); if (this.gamepad) { for (let i = 0; i < this.gamepad.buttons.length; i++) { @@ -17,18 +36,30 @@ module.exports = AFRAME.registerComponent("cardboard-controls", { } this.buttons[i] = this.gamepad.buttons[i].pressed; } - } else if (Object.keys(this.buttons)) { + } else if (Object.keys(this.buttons).length) { this.buttons = {}; } }, _getGamepad: function() { - const gamepads = navigator.getGamepads && navigator.getGamepads(); + if (!navigator.getGamepads) { + return null; + } + + const gamepads = navigator.getGamepads(); for (let i = 0; i < gamepads.length; i++) { if (gamepads[i] && gamepads[i].id === CARDBOARD_BUTTON) { return gamepads[i]; } } return null; + }, + + _handleEnterVR: function() { + this.inVR = true; + }, + + _handleExitVR: function() { + this.inVR = false; } });