在下面的代码中,我尝试在addEventListener调用的函数中设置输入变量。我遇到的问题是输入变量' input_left'从未设置为真。 if语句下的代码未运行,但应运行应设置变量的代码。我尝试使用bind()函数,但它没有改变任何内容。
//Player
var Player = function() {
this.input_left = false;
}
Player.prototype.update = function() {
this.input_left = false;
window.addEventListener('keydown', this.keyPressed.bind(this));
if (this.input_left) {
alert('2'); //It doesn't show this
}
}
Player.prototype.keyPressed = function(e) {
switch(e.keyCode) {
case 65:
this.input_left = true;
alert('1'); //It shows this
break;
}
}
//Initialize the object
var player = new Player();
//Game loop
var gameLoop = function() {
player.update();
window.requestAnimationFrame(gameLoop);
}
window.requestAnimationFrame(gameLoop);
我怀疑播放器的this.input_left变量从未正确设置,即使设置它的代码运行,我想知道如何确保变量设置正确以便警报(' 2&#39);运行。
答案 0 :(得分:0)
您应该将事件监听器移动到构造函数(或某些init函数)中,这样就不会反复创建它。
在更新功能中检查之前,您还将input_left设置为false,那么在重置之前如何检查它呢?
//Player
var Player = function() {
this.input_left = false;
window.addEventListener('keydown', this.keyPressed.bind(this));
}
Player.prototype.update = function() {
if (this.input_left) {
console.log('2'); //It shows this
}
this.input_left = false;
}
Player.prototype.keyPressed = function(e) {
switch(e.keyCode) {
case 65:
this.input_left = true;
console.log('1'); //It shows this
break;
}
}
//Initialize the object
var player = new Player();
//Game loop
var gameLoop = function() {
player.update();
window.requestAnimationFrame(gameLoop);
}
window.requestAnimationFrame(gameLoop);