有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

游戏中的java定时器

我正在尝试编写一个2D java游戏。我像往常一样有init()render()update()方法。我想弄清楚的是,我想把计时器连接到物体上。例如,通电会在地图中随机生成,但它应该存在5秒。或者当用户点击“播放”按钮时,我想让他等待3秒钟,同时做背景工作(加载资源、创建场景等)。我的意思是我想让计时器在后台工作,同时我在游戏中正常工作。我如何实现这一点?任何帮助,即使是简单的想法都将不胜感激

编辑:我正在使用slick2D库和图形类来绘制屏幕


共 (1) 个答案

  1. # 1 楼答案

    如果您想使用计时器,有多种方法,如前所述:

    线。睡眠(毫)

    或者我通常使用的另一种方法是创建一个新类,并使用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
           }
        }
    }