1

嗨,我正在尝试为我的游戏使用 requestAnimationFrame,实际上我在下面使用了这段代码,但正如您所见,“.bind()”为每个循环创建了一个新函数,这会减慢我的游戏速度......我正在寻找一个“高效”解决方案以获得最佳性能,提前谢谢您:D

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

    /* here myGameLoop */
  }

  this.loop();
}

上面的代码可以工作,但速度很慢。相反,这个“标准”代码给了我“类型错误”:

window.requestAnimationFrame(this);

我还发现我尝试了这个问答:requestAnimationFrame attach to App object not Window只工作一次然后给出相同的“类型错误”:(

如果您不相信我,请尝试: http: //jsfiddle.net/ygree/1 :'(

4

1 回答 1

1

不知道你的对象的整个故事(里面还有什么);你可以通过这样做来简化生活:

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

现在您不需要绑定任何东西,您可以快速访问本地范围。

然后调用:

var class1 = new myClass();
class1.start();
于 2013-07-05T10:40:49.380 回答