I am working on a little Java game, leaning on the classic Asteroids.
In this game there are a ton of objects which need to be updated in certain time intervals:
Every frame: Objects that move or rotate.
Every second: The game timer.
Every few seconds: Enemy AI, enemy spawning
Every some-second: Firing a new bullet from the ship weapon.
Currently I’m handling it like this:
//This method is called by a timer that is run every 30 milliseconds
//It will iterate through all objects that require periodic updates and call their
//update method every 30ms.
public void frameUpdateLoop(){
for( Updating u : allObjectsThatNeedPeriodicUpdates ){
u.update();
}
}
public class EnemySpawner implements Updating{
private static final int SPAWN_TRESHOLD=500;
private int timeUntilNewEnemySpawns=SPAWN_TRESHOLD;
//This method is called by frameUpdateLoop()
//It is only supposed to do work once every 500ms, but is called every
//30ms nonetheless.
public void update(){
timeUntilNewEnemySpawns -= 30; //Subtract time since last update
if( timeUntilNewEnemySpawns <= 0){
SpawnNewEnemy();
timeUntilNewEnemySpawns = SPAWN_TRESHOLD;
}
}
}
Of course this is only an example of how I am using it, so I removed the unnecessary parts.
My question is:
Is that the right (=a good way) of implementing such an update system?
When reading around I noticed that most of the time a Timer is used for such a task.
But that would require me to have dozens of timers running at once (one for each object that requires updating).
If I understand correctly each instance of a Timer also creates a new thread, so I fear that this could become a problem at some point (thread-handling performance loss outweights my current system – or the number of threads becomes too large).
I’m sort of new to Java so I don’t know if my fears are baseless or if it really is a bad idea to have so many Timers.
Thank you very much for suggestions, tips and corrections on this topic!
I really like your design with
Updatinginterface abstracting the details of what actually has to be updated. Of course your current implementation isn’t very elegant. Maybe you should create several methods likeupdateEveryFrame(),updateEverySecond(), etc.? Each object implements only the methods that it needs to work, leaving others us no-ops.Timeris actually a good choice here as well:However I would recommend splitting
allObjectsThatNeedPeriodicUpdatesinto:allObjectsThatNeedUpdateEveryFrame,allObjectsThatNeedUpdateEverySecond, etc. Create one periodic task for first collection, another (with different interval) for the other.