0

我需要一种在设定时间在关卡中生成对象的方法。我知道我可以通过检查时间变量来使用 If 语句来做到这一点,但这个想法很愚蠢,因为它会检查 ewery 更新是否是正确的时间,这会使我的游戏变慢。还有其他方法吗?我正在用 Java 编程。抱歉英语不好。

4

1 回答 1

2

您需要使用 Java 的 Timer 类,http://docs.oracle.com/javase/6/docs/api/java/util/Timer.html

这是一个简单的例子:

public class Reminder 
{
    Timer timer;

    public Reminder(int seconds) {
        timer = new Timer();
        timer.schedule(new RemindTask(), seconds*1000);
    }

    class RemindTask extends TimerTask {
        public void run() {
            System.out.println("Time's up!");
            timer.cancel(); //Terminate the timer thread
        }
    }

    public static void main(String args[]) {
        new Reminder(5);
        System.out.println("Task scheduled.");
    }
}

在您的实例中,您需要将 timer schedule 方法调用从 seconds 参数替换为 Date 变量。您将使用此构造函数:

schedule(TimerTask task, Date time) 安排指定任务在指定时间执行。

希望这对你有帮助!

于 2015-04-06T15:52:34.510 回答