所以我正在写一个游戏,我有一个模块可以返回当前通过 jQuery 按下的键。那里没有问题。当我尝试访问按下的键时出现问题:
var Keys = require('./lib/keys')
Player.prototype.update = function () {
Keys(function (err, keydown) {
console.log(keydown, keydown['w']);
/* // To move a player up, for example:
if (keydown['w']) {
this.y += this.speed;
}
*/
});
};
控制台显示按下了哪些键,但尝试访问一个键会给我一个未定义而不是真的。
Object undefined
s: true
w: true
x: true
__proto__: Object
有人有什么想法吗?
更新:关键模块
var $ = require('./jquery')
var Keys = function (callback) {
var keydown = {};
function keyName(event) {
return String.fromCharCode(event.which).toLowerCase();
}
$(document).bind('keydown', function (event) {
keydown[keyName(event)] = true;
return false;
});
$(document).bind('keyup', function (event) {
return false;
});
callback(null, keydown);
}
module.exports = Keys;
/ * ** * ** * ** * ** * *更新 * ** * ** * ** * ** * * /
这是最终修复:
./lib/keys.js var $ = require('./jquery')
var Keys = function () {
this.keydown = {};
var keyName = function (event) {
return String.fromCharCode(event.which).toLowerCase();
}
var self = this;
$(document).bind('keydown', function (event) {
self.keydown[keyName(event)] = true;
return false;
});
$(document).bind('keyup', function (event) {
self.keydown[keyName(event)] = false;
return false;
});
};
Keys.prototype.getKeys = function (callback) {
callback(null, this.keydown);
}
module.exports = new Keys;
./lib/player.js var Keys = require('./keys')
var Player = function (game, keys) {
// stuff
}
Player.prototype.update = function() {
var self = this;
Keys.getKeys(function(err, keys) {
if (keys['w']) {
self.y -= self.speed;
}
if (keys['a']) {
self.x -= self.speed;
}
if (keys['s']) {
self.y += self.speed;
}
if (keys['d']) {
self.x += self.speed;
}
});