使用 requestAnimationFrame 的 JS 游戏循环 - 对象函数只调用一次

JS game loop using requestAnimationFrame - object functions are called only once

本文关键字:调用 一次 函数 对象 requestAnimationFrame JS 游戏 循环 使用      更新时间:2023-09-26

对不起,我是js的菜鸟,以为我已经掌握了对象实例和函数的基础知识,结果我没有也不知道如何弄清楚该怎么做。

我已经声明了一个像这样的 GameLoop 函数/对象:

function GameLoop() {
    window.requestAnimationFrame = 
            window.requestAnimationFrame || /* Firefox 23 / IE 10 / Chrome */
            window.mozRequestAnimationFrame || /* Firefox < 23 */
            window.webkitRequestAnimationFrame || /* Safari */
            window.msRequestAnimationFrame || /* IE  */
            window.oRequestAnimationFrame; /* Opera */
    this.start = function() {
        this.update();
    };
    this.update = function() {
        this.processInput();
        this.updateState();
        this.updateGraphics();
        window.requestAnimationFrame(this.update);
    };
    this.processInput = function() {
        alert("pi");
    };
    this.updateState = function() {
        alert("us");
    };
    this.updateGraphics = function() {
        alert("ug");
    };  
};

我正在尝试像这样运行它:

$(document).ready(main);
        function main() {
            var gameLoop = new GameLoop();
            gameLoop.start();
        }

发生的事情是,每个"processInput"updateStaten"和"updateGraphics"函数都被调用一次(我可以看到它们显示的每个警报),但随后它停止并且我得到的错误(在Firefox的错误控制台中)是

Error: TypeError: this.processInput is not a function

指向update函数内的this.processInput()行。

我只是不明白为什么,特别是因为第一次调用函数。谁能帮忙?

您的函数以错误的this运行。

this是根据您调用函数的方式设置的。
当被requestAnimationFrame调用时,this将被window

要解决此问题,您需要在闭包中保留this

var self = this;
requestAnimationFrame(function() { self.processInput(); });

您还可以使用新的 ES5 bind() 函数为您执行此操作:

requestAnimationFrame(this.processInput.bind(this));