1

I'm building a demo with Three.js (even though I want input to work the same way on any library)

I tried researching the subject of user input/events and there are just way to many answers that are using jQuery or some other library or attached to a web element.

I'm just learning so I would like to just stick with Vanilla JS.

I'm just looking for a way that if a keyboard button is pressed example if W pressed then console.log("Key: 'W' was pressed");.

Same for mouse input/event mouse position:

console.log(mouseX + ", " + mouseY);

the problem is finding bare bones samples that are vanilla JS. Just looking for a simple solution that I can later build up on for example:

  1. return true if key or mouse button pressed
  2. get position of mouse x and y
  3. later add event queue for syncing with framerate/loop

I read that events/input can be challenging, just looking for a nudge in the right direction.

P.S. I wouldn't mind using a light weight library that simplifies this with maybe support for touch screens/mobile even controller input.

Mostly for gaming purposes.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
abflett
  • 69
  • 13
  • 1
    Assuming a canvas, http://stackoverflow.com/questions/17130395/canvas-html5-real-mouse-position and http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas for mouse x/y – Firedrake969 May 09 '15 at 19:16
  • var renderer = new THREE.WebGLRenderer(); renderer.setSize( window.innerWidth, window.innerHeight ); document.body.appendChild( renderer.domElement ); – abflett May 09 '15 at 19:23
  • Are you using a `` element (or any element at all, actually)? Should work... – Firedrake969 May 09 '15 at 19:25
  • I believe that three.js will render to a canvas element as a fallback. Looking for events that happen with in the window/screen space of the document not only within a canvas or do I need to create a fake canvas full screen that gets covered by a GL context? (sorry little new for correct wording) – abflett May 09 '15 at 19:44
  • I think you can safely remove tag `three.js`. – Ruslanas Balčiūnas May 09 '15 at 22:22
  • Found the answer @ http://www.kirupa.com/html5/keyboard_events_in_javascript.htm – abflett May 10 '15 at 02:51

1 Answers1

1

I like to use my own modified version of THREEx.KeyboardState for keyboard input. It's not too complicated - it just subscribes to the keyup and keydown events on the document object and buffers all the events each frame. My game calls the update method each frame to cycle the buffer.

document.addEventListener("keydown", this._onKeyDown, false);
document.addEventListener("keyup", this._onKeyUp, false);

I wrote similar for the mouse and also for gamepads in Chrome. They are all fairly clean and straightforward. Hopefully that should give you some good examples to work from.

The source can be viewed on Github in Javascript or Typescript.

BMac
  • 463
  • 3
  • 8