2

これはこのサイトで人気のある質問のようですが、以前の回答ではこの問題のインスタンスは解決されていません。

node.jsサーバーでゲームエンジンの始まりがありますが、それを設定すると、loopメソッドで次のエラーが発生しますObject #<Timer> has no method update

プロトタイプを設定して更新方法を設定していると思いましたGameEngine.prototype.update = function(){ ... };

この問題を解決するための助けをいただければ幸いです。ありがとうございました。

コード全体は次のとおりです。

function GameEngine(){
    this.fps = 1000/60;
    this.deltaTime = 0;
    this.lastUpdateTime = 0;
    this.entities = [];
}

GameEngine.prototype.update = function(){
    for(var x in this.entities){
        this.entities[x].update();
    }
}

GameEngine.prototype.loop = function(){
    var now = Date.now();
    this.deltaTime = now - this.lastUpdateTime;
    this.update();
    this.lastUpdateTime = now;
}

GameEngine.prototype.start = function(){
    setInterval(this.loop, this.fps);
}

GameEngine.prototype.addEntity = function(entity){
    this.entities.push(entity);
}

var game = new GameEngine();
game.start();
4

1 に答える 1

7

これはこのサイトでよくある質問のようです

はい。

しかし、以前の回答では、この問題のインスタンスは解決されていません。

本当?あなたはどれを見つけましたか?


関数がタイムアウト/イベントリスナーなどによって実行されると、「メソッド」( this) のコンテキストが失われます。

GameEngine.prototype.start = function(){
    var that = this;
    setInterval(function(){
       that.loop();
    }, this.fps);
}

また

GameEngine.prototype.start = function(){
    setInterval(this.loop.bind(this), this.fps);
}
于 2012-07-10T18:42:33.013 に答える