Unit 3, lesson 21

Adding a setTimeout? My student wants to add a setTimeout for his program and we are struggling to make this work. Anyone know what the problem is? When it hits the ground he wants it to wait a second before it moves again I think is what he wants?

Here is the code:

//GAME SETUP
var base = createSprite(825,350);
base.setAnimation(“base”);
var player = createSprite(200,300);
player.setAnimation(“player”);
var spike = createSprite(400,300);
spike.setAnimation(“spike”);
var sidewall = createSprite(200,200);
sidewall.visible = 0;
//set properties
player.scale = 0.5;
spike.scale = 0.5;
base.scale = 16.665;
//create the variables
var score = 0;
var alive = 1;
function draw() {
// BACKGROUND
background(“blue”);
//gameloop
if (alive == 1) {
//score countup
score = score + 1;
//floor behaivior
if (keyWentDown(“space”)) {
player.velocityY = -4;
if (player.isTouching(base)) {
player.rotation = 0;
player.velocityY = 0;
} else {
player.velocityY = player.velocityY + 0.5;
player.rotationSpeed = 3;
}
}
}
fill(“black”);
textSize(20);
if ((player.isTouching(spike) || (player.isTouching(sidewall)))) {
alive = 0;
background(“black”);
fill(“fail”);
textSize(50);
text(“Game Over!” , 40, 200);
setTimeout(function() {
alive = 1;
}, 2000);
}
drawSprites();
}

Good morning! Thanks for reaching out to the forum!

One quick observation on the code …. the setTimeout is inside the draw loop, so it is running repeatedly and causing the timeouts to happen over and over again.

Maybe try maybe some code like this to calculate the time of death and then a conditional statement later that reacts 2000 milliseconds (2 seconds) after the death.

if (alive == 1 && (player.isTouching(spike) || player.isTouching(sidewall))) {
alive = 0;
deathTime = millis();
}

In this code, millis() returns the number of milliseconds since the program started so you have a frame of reference and can use the deathTime variable and millis() in another conditional as a trigger to move on.

Hope this helps!

Mike