1

我正在玩用 JS 制作游戏。并撞上了无法从主 html 文件中的事件更改变量的砖墙。即说offSetX。为什么不改变?

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);
    }
};
4

1 回答 1

2

试试这个:

window.addEventListener("keyup", function(key){
   game.input.apply(game,[key]);
});

问题出window.addEventListener("keyup", game.input)在行上,您正在为window对象添加处理程序,这就是为什么在input方法中"this"window对象(没有任何"offSetX"方法),而不是game对象。

于 2012-04-15T13:10:09.583 回答