0

This question is for a game I am working on in the Game Lab in Code.org. The game in question will be like a skydiving game, where obstacles spawn at random intervals (between 1000 and 3000 ms). Here is the code:

World.frameRate = 10;
var rects = createGroup();
var timeout = Math.round(randomNumber(800, 3000) / 100) * 100;

function draw() {
  background("white");
  drawSprites();
  if (World.frameCount === Math.round(randomNumber(1000, 3000) / 100) * 100) {
    World.frameCount = 0;
    creation();
  }
}

function creation() {
  var obstacle = createSprite(randomNumber(100, 300), 200, 50, 20);
  obstacle.velocityY = -2;
}
/*
setInterval(function() {
  creation();
}, Math.round(randomNumber(800,3000)/100)*100);
*/

In order to create the spawning mechanism, I tried using the setInterval() and setTimeout() functions, but with those two, on the first execution, it creates a random number, and from there, continues to spawn objects at the same interval. I couldn't find any workarounds around this, so I moved on to World.frameCount. This concept works, however, due to the === operator, obstacles will only spawn between 1 and 3 seconds, after 3 seconds, objects will not be able to spawn. In order to fix this, I added in line 9 (World.frameCount = 0;). When run, this produces an error:

ERROR: Line: 9: TypeError: Cannot set property frameCount of #<Object> which has only a getter

I understand that this error is because you cannot alter the value of World.frameCount. Are there any workarounds to this? I would also appreciate any suggestions on other ways this can be done.

Here's the link to the Code.org project: Skydive v1.0

Ishaan Masil
  • 65
  • 1
  • 9

1 Answers1

1

I don't think you want to set World.frameCount. If you want to spawn objects at a variable interval, use this:

(function timeoutHandler() {
  creation();
  setTimeout(timeoutHandler, randomNumber(800,3000)/100)*100);
})();
D. Pardal
  • 6,173
  • 1
  • 17
  • 37