hi i'm trying to use requestAnimationFrame for my game and I actually use this code below, but as you can see ".bind()" create every loop a new function that slow down my game... I'm looking for a "efficient" solution for the best perfomance, thank you in advance :D

function myClass() {
  this.loop = function() {
    window.requestAnimationFrame(this.loop.bind(this));

    /* here myGameLoop */
  }

  this.loop();
}

above code works but is slow.. instead this "standard" code give me "Type error":

window.requestAnimationFrame(this);

I have also found e tried this Q&A: requestAnimationFrame attached to App object not Window works just ONE time then give the same "Type error" :(

try if you don't believe me: http://jsfiddle.net/ygree/1 :'(

有帮助吗?

解决方案

Without knowing the whole story of your object (what else is in there); you could simplify life by just doing this:

function myClass() {

    var iHavAccessToThis = 1;

    function loop() {

        iHavAccessToThis++;

        /* here myGameLoop */

        requestAnimationFrame(loop);
    }
    loop();

    //if you need a method to start externally use this instead of the above line
    this.start = function() { loop() }

    //...
    return this;
}

Now you don't need to bind anything and you access local scope which is fast.

And then call:

var class1 = new myClass();
class1.start();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top