From f5944d59c28f9aa1de7c6d0e4070486143ec50de Mon Sep 17 00:00:00 2001
From: Kevin Lee <kevin@infinite-lee.com>
Date: Thu, 10 May 2018 11:50:59 -0700
Subject: [PATCH] cleanup; adding additional checks for whether on mobile and
 VR (otherwise don't bother polling the gamepad api)

---
 src/components/cardboard-controls.js | 37 +++++++++++++++++++++++++---
 1 file changed, 34 insertions(+), 3 deletions(-)

diff --git a/src/components/cardboard-controls.js b/src/components/cardboard-controls.js
index ebfc47167..8b4ea1416 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;
   }
 });
-- 
GitLab