2013-06-06 39 views
0

我在run()方法中有一個簡單的遊戲循環。該班正在執行Runnable。我只是想創建一些簡單的時間碼來跟蹤玩家一直在玩的時間。假設我想在兩分鐘後結束遊戲。run()方法中的時間

我不知道我這樣做是正確的,因爲我在屏幕上的時間不是秒,它的時間格式是long,比如1370502588.我做錯了什麼?

這裏是run()方法中的代碼的一部分:

// Game loop --------------------------------------- 
@Override 
public void run() { 
// TODO Auto-generated method stub 

// Time 
long startGameTime = 0; 
long milliSeconds; 
int seconds; 

while (gameRunning) { 
    if (!surfaceHolder.getSurface().isValid()) 
    continue; 

    try { 
    milliSeconds = System.currentTimeMillis() - startGameTime; 
    seconds = (int) (milliSeconds/1000); 
    if (seconds > 120) 
     // Game over 
     canvas = surfaceHolder.lockCanvas(); 
     ... 

編輯:logcat的

06-06 07:27:06.831: E/Trace(864): error opening trace file: No such file or directory (2) 
06-06 07:27:07.601: D/libEGL(864): loaded /system/lib/egl/libEGL_emulation.so 
06-06 07:27:07.611: D/(864): HostConnection::get() New Host Connection established 0x2a142400, tid 864 
06-06 07:27:07.721: D/libEGL(864): loaded /system/lib/egl/libGLESv1_CM_emulation.so 
06-06 07:27:07.721: D/libEGL(864): loaded /system/lib/egl/libGLESv2_emulation.so 
06-06 07:27:07.731: D/dalvikvm(864): GC_CONCURRENT freed 232K, 10% free 7430K/8199K, paused 99ms+117ms, total 354ms 
06-06 07:27:07.801: W/EGL_emulation(864): eglSurfaceAttrib not implemented 
06-06 07:27:07.821: D/OpenGLRenderer(864): Enabling debug mode 0 
06-06 07:27:08.121: I/Choreographer(864): Skipped 35 frames! The application may be doing too much work on its main thread. 
06-06 07:27:08.201: W/dalvikvm(864): threadid=12: thread exiting with uncaught exception (group=0x40a13300) 
06-06 07:27:08.211: E/AndroidRuntime(864): FATAL EXCEPTION: Thread-88 
06-06 07:27:08.211: E/AndroidRuntime(864): java.lang.IllegalArgumentException 
06-06 07:27:08.211: E/AndroidRuntime(864): at android.view.Surface.unlockCanvasAndPost(Native Method) 
06-06 07:27:08.211: E/AndroidRuntime(864): at android.view.SurfaceView$4.unlockCanvasAndPost(SurfaceView.java:785) 
06-06 07:27:08.211: E/AndroidRuntime(864): at se.test.game.GameLoop.run(GameLoop.java:269) 
06-06 07:27:08.211: E/AndroidRuntime(864): at java.lang.Thread.run(Thread.java:856) 
+0

你可以發佈你的logcat嗎?你是否從timertask更新ui? – Raghunandan

回答

4

代替

long startGameTime = 0; 

long startGameTime = System.currentTimeMillis(); 

那麼,這條線,你已經有了更有道理:當前時間

milliSeconds = System.currentTimeMillis() - startGameTime; 

在你的版本,你減去0,這意味着用戶自1970年1月1日一直在打。在我的版本中,你從當前時間減去實際的開始時間,結果是這兩個時刻之間的時間跨度。

+0

1:0,你現在擊敗了我:) +1 – Andremoniy

+0

@Andremoniy:現在我們甚至;) – jlordo

+0

ops,對不起,當然是1:1 :) – Andremoniy

0

startGameTime sis始終爲0,因爲它在本地運行()並且從不更新。