Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to handle periodic updating of many objects?
    primarykey
    data
    text
    <p>I am working on a little Java game, leaning on the classic Asteroids.</p> <p>In this game there are a ton of objects which need to be updated in certain time intervals:</p> <p>Every frame: Objects that move or rotate.<br/> Every second: The game timer.<br/> Every few seconds: Enemy AI, enemy spawning<br/> Every some-second: Firing a new bullet from the ship weapon.</p> <p>Currently I'm handling it like this:</p> <pre><code>//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 &lt;= 0){ SpawnNewEnemy(); timeUntilNewEnemySpawns = SPAWN_TRESHOLD; } } } </code></pre> <p>Of course this is only an example of how I am using it, so I removed the unnecessary parts.</p> <p>My question is: <em>Is that the right (=a good way) of implementing such an update system?</em> When reading around I noticed that most of the time a Timer is used for such a task.</p> <p>But that would require me to have dozens of timers running at once (one for each object that requires updating). <br/> 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).</p> <p>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.</p> <p>Thank you very much for suggestions, tips and corrections on this topic!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload