簡體   English   中英

如何跟蹤Java的第三方API“L​​ibGDX”中的已用時間?

[英]How do i keep track of elapsed time in Java's 3rd party API “LibGDX”?

我正在制作一個游戲,其中玩家(“鮑勃”)垂直移動並持續收集硬幣。 如果玩家沒有設法收集任何硬幣5秒鍾,“鮑勃”開始下降。 隨着時間的推移,他會更快倒下。

我的問題是: 如何跟蹤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;
       }

並且將世界級的收集方法稱為 -

  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();
   }

我是這樣做的

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

  }
}

看到這個答案有很多觀點,我應該指出接受答案的問題並提供替代解決方案。

由於下面一行代碼導致的舍入,你的“計時器”會慢慢漂移你運行程序的時間越長:

time = 0;

原因是if條件檢查時間值是否大於或等於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;
    }
}

在快速測試期間,您很可能不會注意到這個微妙的問題,但如果您仔細查看事件的時間安排,運行應用程序幾分鍾就可能會開始注意到它。

你試過使用Gdx.graphics.getElapsedTime()
(不確定具有確切的功能名稱)

構建0.9.7中的方法是'Gdx.graphics.getDeltaTime()',因此上述建議絕對是現場的。

它的

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM