&引用;背景“;使用javascript和html5的游戏动画

&引用;背景“;使用javascript和html5的游戏动画,javascript,html,inheritance,canvas,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.fil

假设我的基类如下所示:

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之间波动,这样它就会不断地淡入淡出,但我希望这是独立于“游戏循环”的。(这样,无论游戏速度如何,淡入淡出的动画都是平滑的)

我不知道该怎么做,但我有一个想法,在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.prototype=new Tile();
Apple.prototype.constructor=Apple;
功能苹果(obj){
var动画方向;
var animate=setInterval(this.Draw,50);
应用(这个,参数);
}
Apple.prototype.Draw=函数(){
ctx.fillStyle=“rgba(“+this.Red+”、“+this.Green+”、“+this.Blue+”、“+this.Opacity+”);
ctx.fillRect(this.X,this.Y,this.Width,this.Height);
如果(this.Opacity=1){
this.AnimationDirection=-0.1;
}
this.Opacity+=this.AnimationDirection;
};
当调用第一个Apple.Draw()时,它的工作方式与您预期的一样,但是来自setInterval的调用无法正常工作。有什么想法吗


(另外,Draw函数中的两条ctx线在Tile和Apple类中都是重复的,我有没有办法把它踢到Tile父级进行填充,而不是重复代码?

我相信原因是当
Draw()
函数作为
setInterval
调用的一部分触发时,
这不是你想象的那样

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

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

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

您还可以通过在Apple的
Draw()中使用
Tile.Draw来避免重复
函数,而不是两行
ctx…
行。此外,以下文章可能有助于为您澄清与此相关的一些事项:
function Apple(obj) {
    var AnimationDirection, me = this;
    var animate = setInterval(function() {
        me.Draw();
    }, 50);
    Tile.apply(this, arguments);
}