How to create better timers?

Hi!
So I have experimented with timers before (on a basic level), but never got anything elegant. Actually I think my approach is pretty messy. I’m working on a small game at the moment, and want to add more objects to an ArrayList over time. This is how I did it:

void draw(){ // simplification
  void addNewTargetObjects(){
    if(timeSinceStart() >= 5000)
      targetList.add(new Target());
   }
}

timeSinceStart() is:

  float timeSinceStart(){
    float timeSinceStart = dist(millis(), 0, startTime, 0); 
    return timeSinceStart; // float startTime = time the game was started/reset
  }

But this means that another object is being added every single frame. That’s a liiiiittle bit to much. I would solve this problem by creating a boolean that stores whether the object was already added or not, but that creates just so many unnecessary variables/aka a big array. I just don’t like that method. Do you have any ideas?

1 Like

I guess I could ask if targetList.size() is equal to something in this case…

if(timerSinceStart() >= 5000 && targetList.size() == 1){
   ...
}

…but I’m rather looking for a general answer here.:grinning:

It sounds like you just need to update the startTime variable, or use a boolean variable to track whether the event has already happened.

You could get more advanced and encapsulate this logic in a class. Then if you wanted one-time behaviors, you could remove the instance after it fires.

Also note that this line:

float timeSinceStart = dist(millis(), 0, startTime, 0); 

Can just be this:

float timeSinceStart = millis() - startTime; 
2 Likes

Thanks, I think I’ll try to create a class for that :smiley:

2 Likes