[英]How to keep track of the elapsed time in a tick method?
In a tick() method, you can't have an int startTime = System.nanoTime() because it will constantly be updating it. 在tick()方法中,不能有一个int startTime = System.nanoTime(),因为它将不断更新它。
I need to find the elapsed time within the tick method , so that every 2 seconds a new object gets spawned. 我需要在tick方法中找到经过的时间 ,以便每2秒产生一个新对象。
public void tick() {
long startTime = System.nanoTime();
// wave 1
if (wave == 1) {
float k = System.nanoTime() - startTime;
/* won't work because "startTime" is constantly updating */
if (k >= 2 && k <= 3) {
handler.addObject(new BasicEnemy());
} else if (k >= 4 && k <= 5) {
handler.addObject(new BasicObject());
} else if (k >= 6 && k <= 7) {
handler.addObject(new BasicEnemy());
}
}
// wave 2
if (wave == 2) {
float k = System.nanoTime() - startTime;
/* won't work because "startTime" is constantly updating */
if (k >= 2 && k <= 3) {
handler.addObject(new BasicEnemy());
} else if (k >= 4 && k <= 5) {
handler.addObject(new BasicObject());
} else if (k >= 6 && k <= 7) {
handler.addObject(new BasicEnemy());
}
}
}
}
The above is a small snippet of the code. 上面是代码的一小段。 How would I go about finding the elapsed time in the tick method and having it restart its count for every if statement?
我该如何在tick方法中找到经过的时间,并让它重新开始每个if语句的计数?
Thanks for the help :) 谢谢您的帮助 :)
You would need to hold the timeAtLastAccept
outside the tick()
method like so: 您将需要在
tick()
方法外部保存timeAtLastAccept
,如下所示:
long timeAtLastAccept = System.nanoTime();
public void tick(){
if(System.nanoTime()-timeAtLastAccept >threshold) {
//Spawn your objects!
timeAtLastAccept = System.nanoTime();
}
//do ticky things
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.