Advertisement
vedi0boy

GameThread

Dec 31st, 2013
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. package me.vedi0boy.anaglyph;
  2.  
  3. import android.graphics.Canvas;
  4. import android.util.Log;
  5. import android.view.SurfaceHolder;
  6.  
  7. public class MainThread extends Thread{
  8.  
  9. private static final String TAG = MainThread.class.getSimpleName();
  10. private SurfaceHolder holder;
  11. private Anaglyph gamePanel;
  12.  
  13. private final static int MAX_FPS = 50;
  14. private final static int MAX_FRAME_SKIPS = 5;
  15. private final static int FRAME_PERIOD = 1000 / MAX_FPS;
  16.  
  17. public MainThread(SurfaceHolder holder, Anaglyph gamePanel){
  18. super();
  19. this.holder = holder;
  20. this.gamePanel = gamePanel;
  21.  
  22. }
  23.  
  24. public static boolean running = false;
  25. public void setRunning(boolean running){
  26. this.running = running;
  27. }
  28.  
  29. public void run(){
  30. Canvas canvas;
  31. long beginTime;
  32. long timeDiff;
  33. int sleepTime;
  34. int framesSkipped;
  35. sleepTime = 0;
  36. Log.d(TAG, "Starting Game Loop");
  37. while(running){
  38. canvas = null;
  39. Log.d(TAG,"Game loop running!");
  40. try{
  41. canvas = this.holder.lockCanvas();
  42. synchronized (holder){
  43. beginTime = System.currentTimeMillis();
  44. framesSkipped = 0;
  45. if(canvas != null){
  46. this.gamePanel.update();
  47. this.gamePanel.render(canvas);
  48. }
  49. timeDiff = System.currentTimeMillis()- beginTime;
  50. sleepTime = (int)(FRAME_PERIOD - timeDiff);
  51. if(sleepTime > 0){
  52. try{
  53. Thread.sleep(sleepTime);
  54. }catch(InterruptedException e){}
  55. }
  56. }
  57. while(sleepTime < 0 && framesSkipped < MAX_FRAME_SKIPS){
  58. if(canvas != null){
  59. this.gamePanel.update();
  60. }
  61. sleepTime += FRAME_PERIOD;
  62. framesSkipped++;
  63. }
  64. } finally{
  65.  
  66. if(canvas != null){
  67. holder.unlockCanvasAndPost(canvas);
  68. }
  69.  
  70. }
  71. }
  72. }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement