2016-05-11 89 views
1

我想在每秒鐘(隨機)更改氣球的位置。我寫了這段代碼:如何在LIBGDX中設置計時器

public void render() { 

    int initialDelay = 1000; // start after 1 seconds 
    int period = 1000;  // repeat every 1 seconds 
    Timer timer = new Timer(); 
    TimerTask task = new TimerTask() { 
     public void run() { 
      rand_x = (r.nextInt(1840)); 
      rand_y = (r.nextInt(1000)); 
      balloon.x = rand_x; 
      balloon.y = rand_y; 
      System.out.println("deneme"); 
     } 
    }; 
    timer.schedule(task, initialDelay, period); 

    Gdx.gl.glClearColor(56, 143, 189, 1); 
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); 

    camera.update(); 
    batch.setProjectionMatrix(camera.combined); 

    batch.begin(); 
    batch.draw(balloon, balloon_rec.x, balloon_rec.y); 
    batch.end(); 

} 

initialDelay正在工作。當我運行程序時,氣球的位置在1秒後發生變化。但時期不起作用。哪裏有問題?

回答

3

不要在渲染方法中激發線程,它不安全,會導致線程泄漏,還有很多其他問題,並且將更難以維護代碼,以便處理時間使用變量每次渲染時添加增量時間所謂的,當這個變量是一個優越1.0F意味着那一秒過去了,您的代碼將是這樣的:

  private float timeSeconds = 0f; 
      private float period = 1f; 

      public void render() { 
       //Execute handleEvent each 1 second 
       timeSeconds +=Gdx.graphics.getRawDeltaTime(); 
       if(timeSeconds > period){ 
        timeSeconds-=period; 
        handleEvent(); 
       } 
       Gdx.gl.glClearColor(56, 143, 189, 1); 
       Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); 

       camera.update(); 
       batch.setProjectionMatrix(camera.combined); 

       batch.begin(); 
       batch.draw(balloon, balloon_rec.x, balloon_rec.y); 
       batch.end(); 

      } 

      public void handleEvent() { 
       rand_x = (r.nextInt(1840)); 
       rand_y = (r.nextInt(1000)); 
       balloon.x = rand_x; 
       balloon.y = rand_y; 
       System.out.println("deneme"); 
      } 
+0

謝謝你,它的工作:) – user5535577

+0

很高興幫助:) – Hllink