我不能将setInterval用于类内部的函数

问题描述

我正在用HTML,JavaScript和CSS重新创建Flappy Bird。我从做鸟开始。当我完成fall函数时,我添加了一行代码,每137.5毫秒调用一次。

setInterval(player.fall,137.5);

这没有用,所以我将其更改为调用一个调用player.fall()函数

setInterval(function () {
  player.fall();
},137.5);

那也不起作用。另外,我在控制台中没有任何错误。然后,我尝试了另外一种方法。我创建了一个在其中调用player.fall()函数

function playerFall() {
  player.fall();
}
setInterval(playerFall,137.5);

下面是我的完整玩家课。我的clear()draw()函数未包含在下面的代码中。

class Player {
    constructor (x,y,width,height,speed,fallSpeed,color) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.speed = speed;
        this.fallSpeed = fallSpeed;
        this.color = color;

        this.draw = function () {

            // draws the player
            ctx.fillStyle = this.color;
            ctx.fillRect(this.x,this.y,this.width,this.height);

        }
        this.fall = function () {

            // makes the player move smoother
            let time = 0;
            for (let i = 0; i < 6; i++) {
                setTimeout(function () {
                    clear();
                    this.y += this.fallSpeed;
                    draw();
                },time);
                time += 20;
            }

        }
    }
}

当我从控制台调用player.fall()函数时,该函数未运行。为什么这行不通?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)