2012-02-25 81 views
4

我正在製作一個遊戲,玩家(「Bob」)垂直移動並持續收集硬幣。如果玩家沒有設法收集任何硬幣5秒,「鮑勃」開始下降。隨着時間的推移,他會更快地倒下。我如何跟蹤Java第三方API「L​​ibGDX」中的流逝時間?

我的問題是這樣的:如何跟蹤LibGDX(Java)應用程序中的流逝時間?

示例代碼如下。

public void update (float deltaTime) 
{ 
`velocity.add(accel.x * deltaTime,accel.y*deltaTime);` 

    position.add(velocity.x * deltaTime, velocity.y * deltaTime); 
    bounds.x = position.x - bounds.width/2; 
    bounds.y = position.y - bounds.height/2; 
    if (velocity.y > 0 && state == BOB_COLLECT_COINE) 
    { 
    if (state== BOB_STATE_JUMP) 
     { 
     state = BOB_STATE_Increase; 
     stateTime = 0; 
    } 
    else 
    { 
    if(state != BOB_STATE_JUMP) 
    { 
     state = BOB_STATE_JUMP;//BOB_STATE_JUMP 
     stateTime = 0; 

     } 
     } 
    } 

    if (velocity.y < 0 && state != BOB_COLLECT_COINE) 
     { 
     if (state != BOB_STATE_FALL) { 
     state = BOB_STATE_FALL; 
     stateTime = 0; 
     } 
    } 
     if (position.x < 0) position.x = World.WORLD_WIDTH; 
    if (position.x > World.WORLD_WIDTH) position.x = 0; 

     stateTime += deltaTime; 
    } 



    public void hitSquirrel() 
     { 
     velocity.set(0, 0); 
     state = BOB_COLLECT_COINE;s 
     stateTime = 0; 
     } 

    public void collectCoine() 
     { 

     state = BOB_COLLECT_COINE; 
     velocity.y = BOB_JUMP_VELOCITY *1.5f; 
     stateTime = 0; 
     } 

,並呼籲在世界級的collectmethod在upate作爲鮑勃 -

private void updateBob(float deltaTime, float accelX) 
    { 

    diff = collidetime-System.currentTimeMillis(); 
    if (bob.state != Bob.BOB_COLLECT_COINE && diff>2000) //bob.position.y <= 0.5f) 
    { 
    bob.hitSquirrel(); 
    } 

回答

6

看到這個答案如何有大把的意見,我要指出的問題與接受的答案,並提供了一個替代的解決方案。

你的「定時器」將慢慢漂的時間越長你運行,因爲由下面的代碼行鈍化而引起的程序:

time = 0; 

的原因是,如果條件檢查,如果時間值大於或等於到5(很可能由於四捨五入誤差和幀之間的時間差異而變得更大)。一個更強大的解決方案是不是「重置」的時間,但減去你的等待時間:

private static final float WAIT_TIME = 5f; 
float time = 0; 

public void update(float deltaTime) { 
    time += deltaTime; 
    if (time >= WAIT_TIME) { 
     // TODO: Perform your action here 

     // Reset timer (not set to 0) 
     time -= WAIT_TIME; 
    } 
} 

你很可能在快速測試沒有注意到這個微妙的問題,但運行的應用程序的一對夫婦的如果您仔細查看事件的時間,您可能會開始注意到它的分鐘數。

+0

你是對的我沒想過 – Tiarsoft 2013-08-04 00:59:37

4

你試圖使用Gdx.graphics.getElapsedTime()
(不準確的函數名確定)

的方法在build 0.9.7中是'Gdx.graphics.getDeltaTime()',所以上面的建議絕對是現場。

+3

該方法不存在 – YaW 2012-07-03 15:25:22

+2

如答案所述,使用'Gdx.graphics.getDeltaTime();'。 – aaronsnoswell 2013-02-04 02:37:13

6

我做到了這樣的

float time=0; 

public void update(deltaTime){ 

    time += deltaTime; 
    if(time >= 5){ 
    //Do whatever u want to do after 5 seconds 
    time = 0; //i reset the time to 0 

    } 
} 
1

float time = 0; 


//in update/render 
time += Gdx.app.getGraphics().getDeltaTime(); 
if(time >=5) 
{ 
    //do your stuff here 
    Gdx.app.log("timer ", "after 5 sec :>"); 
    time = 0; //reset 
}