Make a Sprite Appear at a Random Time

I have a student who is creating a game in the Game Lab and he was to make sprites appear at a random location at a random time. I can help him with random location but I am not sure I know how to do “random time” Any help out there? Thanks for any suggestions!

@jarvin, That’s a fun challenge! Yes, it’s possible. There is a function in javaScript called “setTimeout” Code.org even has documentation on it here: setTimeout Information

I don’t see it as an available block, though, so you would have to temporarily switch to text mode and type the code and then return to block mode if you wanted.

Here’s a quick demonstration I threw together that has a mouse appear after a random number of seconds. I set it up so the number of seconds also prints at the bottom of the page. I hope it’s something your student can start with!

Randomly Appearing Mouse

Mike

p.s. another function that might also be useful is setInterval (documentation). It could allow your sprite to show up and then disappear at a set (or random) interval. The documentation even mentions a “Whack a Mole” type game which is what I first thought of when I read your question.

1 Like

function draw() {

if (randomNumber(0,15) === 0) {

sprite.visible = true;
sprite.x = randomNumber(0,400);
sprite.y = randomNumber(0,400);

}

}

1 Like