I am trying to make a simple game using libgdx. One thing that I am stuck with is making enemies spawn at specific times. If I do something like
if (t == 10)
new Enemy();
I might miss this specific time or maybe spawn the same enemy twice. What I have right now is something like
float t = 0
float timeElapsed = 0;
update (float delta) {
timeElapsed += getDeltaTime();
if (timeElapsed > 0.1) {
t++;
timeElapsed = 0;
}
}
This gives me the approximate elapsed time in tenths of seconds for t, but it really doesn’t feel like the way I should be doing this.
I have a solution I use in my games that might be useful. I actually created a Timer class:
You initialize the Timer to a certain time period, then in your update(delta) method you call Timer.update(delta) on all your Timers, then check if any of the timers have elapsed by calling Timer.hasTimeElapsed().
In your case, you only need one Timer object, since the enemies are spawned in sequence. Once you spawn an enemy, you reset the Timer (changing the spawn period if you want) and wait for it to go off again.
You can also modify the Timer object to use the subject-observer pattern in order to trigger callbacks when a timer goes off. This is useful if you have logic that needs to know when a timed event occurs, but the logic does not have direct access to the delta time.