javascript - "Background"使用 javascript 和 html5 的游戏动画

标签 javascript html inheritance canvas

假设我的基类如下:

function Tile(obj) {
    //defaults (alot of variables here like colors and opacity)
}
Tile.prototype.Draw = function () {
    ctx.fillStyle = "rgba(" + this.Red + "," + this.Green + "," + this.Blue + "," + this.Opacity + ")";
    ctx.fillRect(this.X, this.Y, this.Width, this.Height);
};

我的继承自 Tile 类的类

Apple.prototype = new Tile();
Apple.prototype.constructor = Apple;
function Apple(obj) {
    Tile.apply(this, arguments);
}

所以我想对我的苹果对象做的是让它的不透明度在 0 和 1 之间波动,以便它不断淡入和淡出,但我希望这独立于“游戏循环”发生。 (这样无论游戏速度如何,淡入淡出的动画都很流畅)

    function StartGameLoop() {
        console.log("*** Starting Game ***");
        gameLoop = setInterval(Game, gameSpeed);
    }

    function Game() {
        if (!IS_GAME_ON) {                          // Did the game end?
            EndGame();
        } else if (!PAUSE) {                        // Is the game not paused?
            console.log("Tick");
            Logic();                                // do any math
        }
    }

我不知道该怎么做,但我想在 Apple 构造函数中放置一个 setInterval,它一遍又一遍地调用 draw 函数,但我无法让它工作。像这样:

Apple.prototype = new Tile();
Apple.prototype.constructor = Apple;
function Apple(obj) {
    var AnimationDirection;
    var animate = setInterval(this.Draw, 50);
    Tile.apply(this, arguments);
}
Apple.prototype.Draw = function () {
    ctx.fillStyle = "rgba(" + this.Red + "," + this.Green + "," + this.Blue + "," + this.Opacity + ")";
    ctx.fillRect(this.X, this.Y, this.Width, this.Height);

    if (this.Opacity <= 0) {
        this.AnimationDirection = 0.1;
    }
    else if (this.Opacity >= 1) {
        this.AnimationDirection = -0.1;
    }

    this.Opacity += this.AnimationDirection;
};

当第一个 Apple.Draw() 被调用但来自 setInterval 的调用无法正常工作时,它的工作方式与您预期的一样。有任何想法吗?

(PS:Draw 函数中的两条 ctx 行在 Tile 和 Apple 类中都重复,有什么办法可以将它踢到 Tile 父级进行填充而不是重复代码?)

最佳答案

我认为原因是当 Draw() 函数作为 setInterval 调用的一部分触发时,this 不是您想要的认为是。

相反,当 this 引用创建的 Apple 对象时,在构造函数中使用一个变量来存储它的值,并为 setInterval() 使用一个匿名函数来能够引用该新变量并在其上正确调用 Draw() 函数,例如像这样的东西:

function Apple(obj) {
    var AnimationDirection, me = this;
    var animate = setInterval(function() {
        me.Draw();
    }, 50);
    Tile.apply(this, arguments);
}

由于您现在正在 Apple 对象(而不是全局窗口)上调用 Draw() 方法,this 将正确引用到那个对象。

关于javascript - "Background"使用 javascript 和 html5 的游戏动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9357833/

相关文章:

javascript - 对话框未打开 ajax jquery MVC2 asp.net

java - 从 JSP 读取不同的参数到 Servlet

html - 如何在 1 个父 div 内并排放置 3 个 div,并且宽度占页面的 75%?

javascript - 为什么本地存储在javascript之后最后保存

javascript - Highcharts 中的多个 X 轴值

c++ - 如何解决 C++ 中的网格继承问题

javascript - 为什么我不能覆盖类(函数)描述中的方法定义?

c# - 使两个并行继承结构跨层交互的方法

javascript - 在 Angular2 中设置距离另一个元素的元素高度

javascript - 获取 DOM 的文本值并显示在 dat.gui 字段中