Skip to content

Instantly share code, notes, and snippets.

@lynxerzhang
Created April 18, 2017 10:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lynxerzhang/0d62a35be8aa553e4c448cb005fda22d to your computer and use it in GitHub Desktop.
Save lynxerzhang/0d62a35be8aa553e4c448cb005fda22d to your computer and use it in GitHub Desktop.
js keyboard manager
//如下demo使用es5语法编写(实现一个js版的KeyBoardManager,该KeyBoardManager的实现参考自https://github.com/richardlord/Actionscript-Toolkit)
//@see http://www.crockford.com/javascript/inheritance.html
//该方法的目的是每次为自定义构造函数在原型上添加方法时不用每次都写一遍prototype,而且可以提高代码的可读性.
Function.prototype.addMethod = function(funName, fun) {
if(!this.prototype[funName]){
this.prototype[funName] = fun;
}
};
function KeyBoardManager(){
this.buffer = new ArrayBuffer(32 * 8); //该构造函数中定义属性this.buffer, 相当于一个字节数组, 按照8位为一个字节,它拥有32个字节的存储量
this.bufferController = new DataView(this.buffer); //DataView相当于Controller,用于操作ArrayBuffer中的数据
}
//如下利用为Function原型添加的addMethod方法,添加四个属于KeyBoardManager的实例的方法
//console.log(typeof KeyBoardManager); //function
KeyBoardManager.addMethod("isKeyDown", function(keyCode){
return (this.bufferController.getUint8(keyCode >>> 3) & (1 << (keyCode & 7))) != 0;
});
KeyBoardManager.addMethod("isKeyUp", function(keyCode){
return (this.bufferController.getUint8(keyCode >>> 3) & (1 << (keyCode & 7))) == 0;
});
//TODO
KeyBoardManager.addMethod("onKeyDown", function(keyCode){
this.bufferController.setUint8(keyCode >>> 3, this.bufferController.getUint8(keyCode >>> 3) | (1 << (keyCode & 7)));
});
//TODO
KeyBoardManager.addMethod("onKeyUp", function(keyCode){
this.bufferController.setUint8(keyCode >>> 3, this.bufferController.getUint8(keyCode >>> 3) & ~(1 << (keyCode & 7)));
});
(function(window){
var fps = 1;
var keyboardManager = new KeyBoardManager();
//四个测试键的keycode键值
var W = 87;
var A = 65;
var S = 83;
var D = 68;
function render() {
if(keyboardManager.isKeyDown(W)){
console.log("W key down");
}
else if(keyboardManager.isKeyDown(A)){
console.log("A key down");
}
else if(keyboardManager.isKeyDown(S)){
console.log("S key down");
}
else if(keyboardManager.isKeyDown(D)){
console.log("D key down");
}
invalidate();
}
function invalidate() {
setTimeout(function() {
window.requestAnimationFrame(render);
}, 1000 / fps);
}
window.addEventListener("keydown", function(event){
keyboardManager.onKeyDown(event.keyCode);
});
window.addEventListener("keyup", function(event){
console.log(event.key + " is up" + ", keycode is : " + event.keyCode);
keyboardManager.onKeyUp(event.keyCode);
});
invalidate();
})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment