2

This seems to be a popular question on this site but previous answers haven't solved this instance of the problem.

I have the beginnings of a game engine on a node.js server but when I set it going I get the following error occuring in the loop method: Object #<Timer> has no method update.

I thought I was setting the prototype to have an update method with GameEngine.prototype.update = function(){ ... };

Any help in solving this problem would be much appreciated. Thank you.

Here's the entire code:

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();
2
  • when you call this.entities[x].update(), what does it call exactly ? what if you try this.entities[0].update() ? Commented Jul 10, 2012 at 18:43
  • 2
    for..in loops should not be used for arrays. Commented Jul 10, 2012 at 18:43

1 Answer 1

7

This seems to be a popular question on this site

Yes.

but previous answers haven't solved this instance of the problem.

really? Which ones have you found?


The context of the "method" (this) is lost when the function is executed by a timeout/event listener/etc.

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

or

GameEngine.prototype.start = function(){
    setInterval(this.loop.bind(this), this.fps);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, when setTimeout calls a function, it sets this to Window.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.