2016-02-28 121 views
-2

我试图编写一个2D java游戏。像往常一样,我有init()render()update()方法。我想弄清楚的是,我希望将定时器附加到对象上。例如,在地图上随机产生一个powerup,但它应该存在5秒钟。或者当用户点击“播放”按钮时,我想让他等待3秒钟,同时做后台工作(加载资源,创建场景等)。我的意思是我想让时间计数器在后台工作,而我通常在游戏中同时处理这些事情。我怎样才能实现这个?任何帮助,即使简单的想法,将不胜感激!定时器在游戏中

编辑:我使用slick2D库和Graphics类来绘制屏幕。

+0

更好的答案,更多的信息将帮助。例如,你使用的是什么GUI库?你在使用游戏引擎库吗?你如何实现你的游戏循环? –

回答

0

如果你想使用计时器有多种方法可以做到这一点,如前所述有:

Thread.sleep(milli);

或另一种方式我通常使用是创建一个新的类,并进行定时有使用while循环:

public class Timer implements Runnable { 

    private long startTime, runTime; 

    public Timer(long runTime){//set runtime 
     this.runTime = runTime; 
    } 

    public void run(){ 
     startTime = System.currentTimeMillis();//gets system's current time in milliseconds 
     while(System.currentTimeMillis() - startTime < runTime){//loops until the current time - the start time is less then the specified run time. 
     //Runs this 
     } 
    } 
} 
0

有几种方法可以“暂停”执行。这是两个:

  • 可以使用delay(milliseconds)Robot
  • 或静态方法Thread.sleep(milliseconds)
+0

事情是我不想暂停执行,我需要跟踪游戏中出现的一些对象的时间跟踪。这就是为什么当我使用时间计数器时游戏必须继续 –