1
我当时在玩JS游戏。并击中一个砖墙,无法从主html文件中的事件更改变量。就是说关闭SetX。为什么它不会改变?不能从外部事件中更改对象变量
var game = new Game();
window.addEventListener("keyup", game.input);
game.start('myCanvas');
游戏对象看起来像这样。
function Game() {
this.offSetX = 0;
this.init = function (id) {
this.canvas = document.getElementById(id);
this.context = this.canvas.getContext('2d');
this.blocks = [];
this.blocks.push(new block());
};
this.logic = function() {
for (var i in this.blocks) {
this.blocks[i].update(this.offSetX);
}
};
this.draw = function() {
for (var i in this.blocks) {
this.blocks[i].draw(this.context);
}
};
this.main = function() {
this.logic();
this.draw();
console.log(this.offSetX);
};
this.input = function (key) {
if (key.keyCode == 37) {
this.offSetX--;
console.log(this.offSetX);
}
if (key.keyCode == 39) {
this.offSetX++;
console.log(this.offSetX);
}
};
this.start = function (id) {
var _this = this;
this.init(id);
this.interval = setInterval(function() {
_this.canvas.width = _this.canvas.width;
_this.main();
}, 30);
}
};
尝试添加'console.log(this)'作为this.input方法的第一行。然后在你编写'window.addEventListener(“keyup”,game.input)''时检查'console',然后用我的答案替换该代码并再次检查。 – Engineer 2012-04-15 13:32:59