Reputation: 321
No matter what I do I cannot get this bit of code to work, the part where you set an interval in the draw method and will call the Loop method 4 times in two seconds, each call displaying a different image. Currently it shows nothing? And the issue is not with an images etc as it works with one image fine. Been at this for 2 days..
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++;
}
}
Upvotes: 0
Views: 83
Reputation: 129001
You've got a few problems:
Explosion.Loop
does not exist; in normal classical languages, your error would be known as "trying to call an instance method as if it were static." What you could do is instead pass Explosion.prototype.Loop
or this.Loop
, but that's no good either: JavaScript's this
is dynamic and you'll end up trying to get and set properties on window
rather than your object.
What you need to do is use this.Loop
, but make sure the this
isn't lost. On newer browsers, that can be done with bind
1:
setTimeout(this.Loop.bind(this), 500);
1 If they're new enough to support canvas
, they probably support bind
.
setTimeout
will only call your function once; if you want it to be called every half a second rather than only once half a second from now, you'll need to use setInterval
instead.
Accessing instance variables as if they were local variables. In several places (for example, frame
in Loop
), you're accessing frame
like this:
frame++;
Unfortunately, frame
is not a local variable; it's a property of this
. Unlike some other languages, you have to explicitly qualify it:
this.frame++;
As previously mentioned, frame
is not the only variable with this problem.
Upvotes: 1