Sam
Sam

Reputation: 23

Can't seem to get setTimeout to work?

var ExplodeFrame = 0;
var ExplodeTimeout;

All this part does it checks when a player hits lava. It works. see commented part for call to animation

if((Player.x  > Lavas[i].x && Player.x  < (Lavas[i].x + Lavas[i].width)) || (Player.x + Player.width  > Lavas[i].x && Player.x + Player.width < (Lavas[i].x + Lavas[i].width)))
  {
    if((Player.y   > Lavas[i].y && Player.y < Lavas[i].y + Lavas[i].height) || (Player.y + Player.height > Lavas[i].y && Player.y + Player.height < Lavas[i].y + Lavas[i].height))
    {
     ExplodeTimeout = setTimeout(DrawSpawnAnimation, 200); //this part is new and might not work
     Player.jumping = false;
     Player.velY = 0;
     Player.velX = 0;
     Player.x = Player.spawnX;

     Player.y = Player.spawnY;
     Player.playerColour = Player.colour;

    }
  }


}

this method does not seem to work for me?

function DrawSpawnAnimation()
{

ExplodeFrame++;
alert("current frame" + ExplodeFrame);
var explodeX = Player.x - 50;
var explodeY = Player.y - 50;

if(ExplodeFrame == 1)
{
ctxAnimation.drawImage(spriteSheet,0,2740,100,100,explodeX,explodeY,100,100);
}
else if(ExplodeFrame == 2)
{
ctxAnimation.drawImage(spriteSheet,100,2740,100,100,explodeX,explodeY,100,100);
}
else if(ExplodeFrame == 3)
{
ctxAnimation.drawImage(spriteSheet,200,2740,100,100,explodeX,explodeY,100,100);
}
else if(ExplodeFrame == 4)
{
ctxAnimation.drawImage(spriteSheet,300,2740,100,100,explodeX,explodeY,100,100);
}
else if(ExplodeFrame == 5)
{
ctxAnimation.drawImage(spriteSheet,400,2740,100,100,explodeX,explodeY,100,100);
}
else
{
ExplodeFrame = 0;
 clearTimeout(ExplodeTimeout);
  ctxAnimation.clearRect(0,0,canvasWidth,canvasHeight);
}

}

It should show an animation at 5 frames a second until its over. That's what I am trying to do.

Upvotes: 1

Views: 113

Answers (3)

Nikola Dimitroff
Nikola Dimitroff

Reputation: 6237

Firstly, replace the if statements with

ctxAnimation.drawImage(spriteSheet,(ExplodeFrame - 1) * 100,2740,100,100,explodeX,explodeY,100,100);

Secondly, you only call the DrawSpawnAnimation method once. In order to actually see the animation you should call it repeatedly. Do that by adding setting another timeout at the end of DrawSpawnAnimation:

function DrawSpawnAnimation()
{
    ...
    if (ExplodeFrame < 5)
    {
         setTimeout(DrawSpawnAnimation, 20);
    }
}

Upvotes: 0

nicholas
nicholas

Reputation: 14563

setTimeout only fires a function once:

http://www.w3schools.com/jsref/met_win_settimeout.asp

It sounds like what you're looking for is setInterval:

http://www.w3schools.com/jsref/met_win_setinterval.asp

Upvotes: 1

Reason
Reason

Reputation: 1430

setTimeout runs your code once. It seems that you are looking for something that runs every 200 milliseconds. For that, use setInterval. It works in the way you are trying to use setTimeout. When you use setInterval, you clear it by calling clearInterval

Upvotes: 0

Related Questions