0

无论我做什么,我都无法让这段代码工作,您在 draw 方法中设置间隔的部分将在两秒内调用 Loop 方法 4 次,每次调用显示不同的图像。目前它什么都没有显示?问题不在于图像等,因为它可以很好地处理一张图像。在这呆了2天。。

 function Explosion() //space weapon uses this
{
this.srcX = 0;
this.srcY = 1250;
this.drawX = 0;
this.drawY = 0;
this.width = 70;
this.height = 70;
this.currentFrame = 0;
this.totalFrames = 10;
this.hasHit = false;
this.frame = 0;

}

Explosion.prototype.draw = function()
{

 if(this.hasHit == true && this.frame < 5)
 {

    var t=setTimeout(Explosion.Loop,500);

 }

 if(this.frame == 5)
 {
 clearTimeout(t);
 this.hasHit = false;
  this.frame = 0;
 }



}

Explosion.prototype.Loop = function()
{

ctxExplosion.clearRect ( 0 , 0, canvasWidth , canvasHeight );

if(this.frame == 1)
{

   ctxExplosion.drawImage(spriteImage,this.srcX,this.srcY,this.width,this.height,this.drawX,this.drawY,this.width,this.height);
   frame++;
}

else if(this.frame == 2)
{

    ctxExplosion.drawImage(spriteImage,this.srcX,(this.srcY + 77),this.width,this.height,this.drawX,this.drawY,this.width,this.height);
   frame++;
}

else if(this.frame == 3)
{
  ctxExplosion.drawImage(spriteImage,this.srcX,(this.srcY + 154),this.width,this.height,this.drawX,this.drawY,this.width,this.height);
   frame++;

}

else if(this.frame == 4)
{
  ctxExplosion.drawImage(spriteImage,this.srcX,(this.srcY + 231),this.width,this.height,this.drawX,this.drawY,this.width,this.height);
   frame++;

}


}
4

1 回答 1

1

你有几个问题:

  1. Explosion.Loop不存在;在正常的古典语言中,您的错误将被称为“尝试调用实例方法,就好像它是静态的一样”。您可以做的是传递Explosion.prototype.Loopor this.Loop,但这也不好:JavaScriptthis是动态的,您最终会尝试获取和设置属性window而不是对象。

    您需要做的是使用this.Loop,但要确保this没有丢失。在较新的浏览器上,可以使用bind1来完成:

    setTimeout(this.Loop.bind(this), 500);
    

    1如果他们足够新来支持canvas,他们可能支持bind

  2. setTimeout只会调用你的函数一次;如果您希望它每半秒调用一次,而不是从现在起仅半秒调用一次,则需要使用它setInterval

  3. 像访问局部变量一样访问实例变量。在几个地方(例如,frameLoop),您可以这样访问frame

    frame++;
    

    不幸的是,frame不是局部变量;它是this. 与其他一些语言不同,您必须明确限定它:

    this.frame++;
    

    如前所述,frame不是这个问题的唯一变量。

于 2013-06-08T23:38:15.797 回答