Last active
March 10, 2016 22:24
-
-
Save sethvincent/38bf33ab9bfe46f32443 to your computer and use it in GitHub Desktop.
idea for controller api
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} | |
} |
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
@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:
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:But that's a little different that what your implementation above would support?