abflett abflett - 2 years ago 119
Javascript Question

Keypress and mouse events

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 que 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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download