java - 如何在 if 语句中使用计时器
问题描述
我需要每隔 x 时间更新游戏中的食物量。我想使用 if 语句,但它不会工作,因为我猜定时器和整数不能一起工作?
Timer timer = new Timer(200, this);
public void update()
{
double dt = 0;
timer += dt;
if(timer > 1000)
{
food++;
timer = 0;
}
}
解决方案
我建议在此使用实时。您只需要有 2 个变量(上次提要的时间和现在的时间)就可以做到这一点。只需计算时间差并将其置于您的 if 条件下。请参考以下示例:
import java.util.Date;
public class Main {
public static Date lastDate = new Date();
public static int food = 0;
public static void main(String args[]) {
System.out.println("Food was added on " + lastDate.toString() + ". Food now is " + food);
while (food < 5) {
update();
}
}
public static void update() {
Date dateNow = new Date();
// in milliseconds
long diff = dateNow.getTime() - lastDate.getTime();
long diffSeconds = diff / 1000 % 60;
// long diffMinutes = diff / (60 * 1000) % 60;
// long diffHours = diff / (60 * 60 * 1000) % 24;
// long diffDays = diff / (24 * 60 * 60 * 1000);
// If more than 5 seconds have passed
if (diffSeconds > 5) { // just change this to your desired interval
lastDate = new Date(); // get the time now
food++; // increment food
System.out.println("Food was added on " + lastDate.toString() + ". Food now is " + food);
}
}
}
输出:
Food was added on Fri Mar 29 09:15:08 SGT 2019. Food now is 0
Food was added on Fri Mar 29 09:15:14 SGT 2019. Food now is 1
Food was added on Fri Mar 29 09:15:20 SGT 2019. Food now is 2
Food was added on Fri Mar 29 09:15:26 SGT 2019. Food now is 3
Food was added on Fri Mar 29 09:15:32 SGT 2019. Food now is 4
Food was added on Fri Mar 29 09:15:38 SGT 2019. Food now is 5