Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

Added the ability to check if a key is down #63

Merged
merged 2 commits into from

3 participants

@mimshwright

When developing games, it's very common to test whether a key is down in a loop rather than relying on key events. This commit adds two methods that let you check to see if a key is down, isKeyPressed() and getPressedKeyCodes().

@perezd

+1 this is super handy.

@madrobby
Owner

This is great and I'd love to add it, but it lacks unit tests (see keymaster.html in the test folder!).

@mimshwright

Added unit tests. See if that works for you.
Note: I did NOT minify the code.

@madrobby madrobby merged commit bfbe4a6 into madrobby:master
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Oct 24, 2012
  1. @mimshwright
Commits on Nov 6, 2012
  1. @mimshwright

    Added unit test

    mimshwright authored
This page is out of date. Refresh to see the latest.
Showing with 79 additions and 3 deletions.
  1. +19 −1 README.markdown
  2. +33 −2 keymaster.js
  3. +9 −0 test.html
  4. +18 −0 test/keymaster.html
View
20 README.markdown
@@ -61,7 +61,7 @@ and `f1` through `f19`.
## Modifier key queries
At any point in time (even in code other than key shortcut handlers),
-you can query the `key` object for the state of modifier keys. This
+you can query the `key` object for the state of any keys. This
allows easy implementation of things like shift+click handlers. For example,
`key.shift` is `true` if the shift key is currently pressed.
@@ -69,6 +69,24 @@ allows easy implementation of things like shift+click handlers. For example,
if(key.shift) alert('shift is pressed, OMGZ!');
```
+## Other key queries
+
+At any point in time (even in code other than key shortcut handlers),
+you can query the `key` object for the state of any key. This
+is very helpful for game development using a game loop. For example,
+`key.isDown(77)` is `true` if the M key is currently pressed.
+
+```javascript
+if(key.isDown("M")) alert('M key is pressed, can ya believe it!?');
+if(key.isDown(77)) alert('M key is pressed, can ya believe it!?');
+```
+
+You can also get these as an array using...
+```javascript
+key.getPressedKeyCodes() // returns an array of key codes currently pressed
+```
+
+
## Scopes
If you want to reuse the same shortcut for seperate areas in your single page app,
View
35 keymaster.js
@@ -28,7 +28,8 @@
'`': 192, '-': 189, '=': 187,
';': 186, '\'': 222,
'[': 219, ']': 221, '\\': 220
- };
+ },
+ _downKeys = [];
for(k=1;k<20;k++) _MODIFIERS['f'+k] = 111+k;
@@ -43,6 +44,10 @@
function dispatch(event, scope){
var key, handler, k, i, modifiersMatch;
key = event.keyCode;
+
+ if (index(_downKeys, key) == -1) {
+ _downKeys.push(key);
+ }
// if a modifier key, set the key.<modifierkeyname> property to true and return
if(key == 93 || key == 224) key = 91; // right command on webkit, command on Gecko
@@ -86,7 +91,14 @@
// unset modifier keys on keyup
function clearModifier(event){
- var key = event.keyCode, k;
+ var key = event.keyCode, k,
+ i = index(_downKeys, key);
+
+ // remove key from _downKeys
+ if (i >= 0) {
+ _downKeys.splice(i, 1);
+ }
+
if(key == 93 || key == 224) key = 91;
if(key in _mods) {
_mods[key] = false;
@@ -130,6 +142,23 @@
_handlers[key].push({ shortcut: keys[i], scope: scope, method: method, key: keys[i], mods: mods });
}
};
+
+ // Returns true if the key with code 'keyCode' is currently down
+ // Converts strings into key codes.
+ function isPressed(keyCode) {
+ if (typeof(keyCode)=='string') {
+ if (keyCode.length == 1) {
+ keyCode = (keyCode.toUpperCase()).charCodeAt(0);
+ } else {
+ return false;
+ }
+ }
+ return index(_downKeys, keyCode) != -1;
+ }
+
+ function getPressedKeyCodes() {
+ return _downKeys;
+ }
function filter(event){
var tagName = (event.target || event.srcElement).tagName;
@@ -178,6 +207,8 @@
global.key.getScope = getScope;
global.key.deleteScope = deleteScope;
global.key.filter = filter;
+ global.key.isPressed = isPressed;
+ global.key.getPressedKeyCodes = getPressedKeyCodes;
if(typeof module !== 'undefined') module.exports = key;
View
9 test.html
@@ -20,6 +20,8 @@
<li>Press 'i'. Switches scope to 'issues'.</li>
<li>Press 'c'. Console should log function call.</li>
<li>Press 'o' or Enter or Cursor &larr;. Console should log function call.</li>
+ <li>Press and hold 'm'. Console should log a message every second.</li>
+ <li>Every second console should log a message listing all the currently pressed keycodes.</li>
</ol>
<p>
@@ -76,6 +78,13 @@
key('/', function(){ console.log('/') });
key('shift+]', function(){ console.log('shift+]') });
+ setInterval(function () {
+ console.log('All keys currently down: ' + key.getPressedKeyCodes());
+ if (key.isPressed(77)) {
+ console.log('M key is currently down');
+ }
+ }, 1000);
+
// document.onkeydown = function(event){
// console.log(event.keyCode);
// }
View
18 test/keymaster.html
@@ -229,6 +229,24 @@
t.assertEqual(1, filterCalls);
t.assertEqual(1, keyCalls);
+ },
+
+ testIsPressed: function (t) {
+ keydown(65);
+ t.assertTrue(key.isPressed(65));
+ t.assertTrue(key.isPressed("a"));
+ keyup(65);
+
+ keydown(66); keyup(66);
+ t.assertFalse(key.isPressed(66));
+ },
+
+ testGetPressedKeyCodes: function (t) {
+ keydown(65); keydown(KEYS.shift);
+ var pressedKeys = key.getPressedKeyCodes();
+ t.assertTrue(pressedKeys.indexOf(65) >= 0);
+ t.assertTrue(pressedKeys.indexOf(16) >= 0);
+ keyup(65); keyup(KEYS.shift);
}
});
</script>
Something went wrong with that request. Please try again.