2015-12-14 16 views
0

即時創建一個類,可以啓動這個遊戲,作爲我的類遊戲的一種方法。正如你可以看到我添加了我的請求動畫幀的方法中的功能,但它給我一個錯誤:「最大調用堆棧大小超出」'超出最大調用堆棧大小'AnimationFrame

function Game(){ 
    this.player = null; 
    this.anim = null; 
} 

Game.prototype.start = function() { 
    this.anim = requestAnimFrame(this.start()); 
    //code 
} 

Game.prototype.end = function() { 
    cancelAnimFrame (this.anim); 
} 

//create game 
var game = new Game(); 

//start game 
game.start(); 

這工作,如果我用這個:

function render(){ 
    requestAnimFrame(render); 
}; 
//start anim 
render(); 

所以我不知道它是如何工作,如果是在一個方法。

這是動畫幀我使用的代碼:

window.requestAnimFrame = (function(){ 
return window.requestAnimationFrame  || 
     window.webkitRequestAnimationFrame || 
     window.mozRequestAnimationFrame || 
     window.oRequestAnimationFrame  || 
     window.msRequestAnimationFrame  || 
     function(callback,element){ 
      window.setTimeout(callback, 1000/60); 
     }; 
})(); 

window.cancelAnimFrame = (function(){ 
return window.cancelAnimationFrame  || 
     window.mozCancelAnimationFrame || 
     function(callback,element){ 
      window.setTimeout(callback, 1000/60); 
     }; 
})(); 

如果你知道我嘗試做的,感謝我不是使用。

+0

Game.prototype.start =函數(){ this.anim = requestAnimFrame(此.start()); //代碼 }看起來像一個無限循環,這可能是爲什麼它打破。 –

+0

'requestAnimFrame' e xpect **函數**,而您傳遞函數的返回值。你必須用'requestAnimFrame(this.start)'替換'requestAnimFrame(this.start())'。 – hindmost

+0

但請求動畫幀是一個循環的權利? –

回答

0
Game.prototype.start = function() { 
    this.anim = requestAnimFrame(this.start()); 
    //code 
} 

對於requestAnimFrame(this.start());,您正在調用本身的啓動,導致無限循環。 。

你應該嘗試requestAnimFrame(this.start);即使它仍然看起來怪怪:(

+0

哦,我明白了,但我該如何解決它? –

+0

我不知道你想做什麼,但是你會每x秒調用一次遊戲實例的開始方法,因爲每次requestAnimFrame調用它的回調函數時,都會調用start函數,然後會觸發另一個requestAnimFrame , 等等。 –

+0

function render(){ requestAnimFrame(render); }; render(); –

1

我找到了答案,問題是,當我打電話:「this.start」「窗口」爲「本」的IM闖民宅,所以問題消失,如果我將它保存爲 '是' 或 '窗口',然後excecute它,謝謝所有。

var Game = function() { 
    this.anim = null; 

} 

Game.prototype.startAnimation = function(){ 
    window.requestAnimFrame(this.startAnimation.bind(this)); 
} 

var game = new Game(); 
game.startAnimation(); 
相關問題