Question

I am attempting to spawn an object after a 1 second delay, every 2 seconds. My attempts, however, result in the object spawning after a 1 second delay, but then at an exceptionally fast past (i.e. much more frequently than every 2 seconds). I cannot figure out why my timer task is spawning the objects so close together. Any help would be great, thanks.

private Array<Rectangle> spacebars;

public void spawnSpacebar() 
{
spacebar = new Rectangle();
spacebar.x = 800;             
spacebar.y = MathUtils.random(0, 480-64);
spacebar.width = 64;
spacebar.height = 64;
spacebars.add(spacebar);
}

Timer.schedule(new Task()
{@Override
public void run() 
  {
  spawnSpacebar();
  }
}
, 1  // (delay)
, 2  // (every x seconds)
);
Was it helpful?

Solution

NOTE: I realized after writing this answer that you're trying to use the LibGDX Timer class. In that case, make sure you're using LibGDX Timer and not the java.util.Timer

Looks like the parameters for schedule() are in milliseconds. From the java documentation:

public void schedule(TimerTask task, long delay, long period)

Parameters: task - task to be scheduled. delay - delay in milliseconds before task is to be executed. period - time in milliseconds between successive task executions.

So try passing 1000 and 2000 instead of 1 and 2.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top