From 9da289ea6217674e1d19f9bd96a5e30fc0b2607b Mon Sep 17 00:00:00 2001 From: Arne van Iterson Date: Thu, 23 Apr 2020 22:30:06 +0200 Subject: [PATCH] Added listen variable to controls This makes it possible to send controls over socket.io --- lib/controls/KeyControls.js | 24 +++++++++++++----------- lib/controls/MouseControls.js | 14 +++++++++----- 2 files changed, 22 insertions(+), 16 deletions(-) diff --git a/lib/controls/KeyControls.js b/lib/controls/KeyControls.js index 1266cc5..96b6e40 100644 --- a/lib/controls/KeyControls.js +++ b/lib/controls/KeyControls.js @@ -1,17 +1,19 @@ class KeyControls { - constructor() { + constructor(listen = true) { this.keys = {}; - // Bind event handlers - document.addEventListener("keydown", e => { - if ([37, 38, 39, 40].indexOf(e.which) >= 0) { - e.preventDefault(); - } - this.keys[e.which] = true; - }, false); - document.addEventListener("keyup", e => { - this.keys[e.which] = false; - }, false); + if (listen) { + // Bind event handlers + document.addEventListener("keydown", e => { + if ([37, 38, 39, 40].indexOf(e.which) >= 0) { + e.preventDefault(); + } + this.keys[e.which] = true; + }, false); + document.addEventListener("keyup", e => { + this.keys[e.which] = false; + }, false); + } } get action() { diff --git a/lib/controls/MouseControls.js b/lib/controls/MouseControls.js index 27925eb..565953e 100644 --- a/lib/controls/MouseControls.js +++ b/lib/controls/MouseControls.js @@ -1,15 +1,19 @@ class MouseControls { - constructor(container) { + constructor(container, listen = true) { this.el = container || document.body; // State this.pos = { x: 0, y: 0 }; this.isDown = false; this.pressed = false; this.released = false; - // Handlers - document.addEventListener("mousemove", this.move.bind(this), false); - document.addEventListener("mousedown", this.down.bind(this), false); - document.addEventListener("mouseup", this.up.bind(this), false); + + if (listen) { + // Handlers + document.addEventListener("mousemove", this.move.bind(this), false); + document.addEventListener("mousedown", this.down.bind(this), false); + document.addEventListener("mouseup", this.up.bind(this), false); + } + } mousePosFromEvent({ clientX, clientY }) {