"背景”;使用javascript和html5的游戏动画

"Background" Game animations with javascript and html5

本文关键字:html5 javascript 游戏动画 使用 quot 背景      更新时间:2023-09-26

假设我的基类如下:

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

当第一个苹果出现时,它的工作原理正如你所期望的那样。Draw()被调用,但来自setInterval的调用无法正常工作。有什么想法吗?

(附言:此外,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将正确引用该对象。