own_logic_thread.adoc 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. = Your Own Logic Thread
  2. :revnumber: 2.0
  3. :revdate: 2020/07/27
  4. You can add AppStates to the SimpleApplication and your whole program will run on a single thread.
  5. This can have benefits, but this Entity System is optimized to run on several Threads.
  6. Because of this, it is recommended that you run the game logic in a separate thread and independent from the framerate.
  7. In this example, we will say that we want to run the game logic every 20 milliseconds. This means 50 updates per second and a tpf value of 0.2f .
  8. == GameLogic class
  9. [source,java]
  10. ----
  11. public class GameLogicThread implements Runnable {
  12. private final float tpf = 0.02f;
  13. private AppStateManager stateManager;
  14. public GameLogicThread(Application app) {
  15. stateManager = new AppStateManager(app);
  16. //add the logic AppStates to this thread
  17. stateManager.attach(new MovementAppState());
  18. stateManager.attach(new ExpiresAppState());
  19. stateManager.attach(new CollisionAppState());
  20. stateManager.attach(new EnemyAppState());
  21. }
  22. public void run() {
  23. stateManager.update(tpf);
  24. }
  25. }
  26. ----
  27. == Application
  28. [source,java]
  29. ----
  30. public class Example extends SimpleApplication {
  31. private EntitySystem entitySystem;
  32. private ScheduledExecutorService exec;
  33. @Override
  34. public void simpleInitApp() {
  35. //Init the Entity System
  36. entitySystem = new EntitySystem(new MapEntityData());
  37. //Init the Game Systems for the visualisation
  38. stateManager.attach(new EntityDisplayAppState(rootNode));
  39. stateManager.attach(new PlayerInputAppState());
  40. //create the Thread for the game logic
  41. exec = Executors.newSingleThreadScheduledExecutor();
  42. exec.scheduleAtFixedRate(new GameLogicThread(this), 0, 20, TimeUnit.MILLISECONDS);
  43. }
  44. public EntitySystem getEntitySystem() {
  45. return entitySystem;
  46. }
  47. @Override
  48. public void destroy() {
  49. super.destroy();
  50. //Shutdown the thread when the game is closed
  51. exec.shutdown();
  52. }
  53. }
  54. ----