Skip to content

Instantly share code, notes, and snippets.

@sethvincent
Last active March 10, 2016 22:24
Show Gist options
  • Save sethvincent/38bf33ab9bfe46f32443 to your computer and use it in GitHub Desktop.
Save sethvincent/38bf33ab9bfe46f32443 to your computer and use it in GitHub Desktop.
idea for controller api
var keyboard = require('controller-keyboard')
var gameState = {
input: {}
}
keyboard.subscribe(function (action, active) {
// active is the current inputs that are active
// this is triggered every time the state of a key has changed
// maybe we would do something like this to the game state:
gameState.input['keyboard'] = active
// except this part could be done with immutable, redux-like dispatches
// action looks like this:
{
type: 'on' || 'off',
value: 'value representing the input',
event: // original event, browser keyboard event, for instance
}
})
var vkey = require('vkey')
module.exports = function createKeyboardController (options) {
var listener = function () {}
var active = {}
document.addactionListener('keydown', function (e) {
var value = vkey[e.keyCode]
active[value] = true
var action = {
type: 'on',
value: value,
event: e
}
listener(action, active)
}, false)
document.addactionListener('keyup', function (e) {
var value = vkey[e.keyCode]
delete active[value]
var action = {
type: 'off',
value: value,
event: e
}
listener(action, active)
}, false)
return {
subscribe: function (cb) {
listener = cb
}
}
}
@freeman-lab
Copy link

@sethvincent cool! Could you add an example of what it might look like for a game to use this to do something like update player movement? Currently, we're doing something like this:

var loop = require('gameloop')()
var controller = require('controller')

loop.on('update', function () {
  player.position = move(player.position, controller.keys)
})

So there's a constantly running gameloop, and we're checking the keyboard state every tick, and moving accordingly.

If we started using a minidux style store to represent state, I guess I imagined something like this:

var controller = require('controller')
var minidux = require('minidux')

// create a state with player position
var state = {
  position: [0, 0]
}

// key on actions update player position
var reducer = function (state, action) {
  if (action.type == 'on') {
   return {position: move(state.position, action.keys)}
  }
}

store = minidux.createStore(reducer, state)

// controller input events trigger dispatches to the store
controller.on('input', function (keys) {
  store.dispatch({type: 'on', value: keys})
})

But that's a little different that what your implementation above would support?

@sethvincent
Copy link
Author

I wonder if it would be easier to have action creators that do things like

move(state.position, action.keys)

And then dispatch the result. That way the reducer stays as simple as possible.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment