我定义一个
int x = 10;
现在,我希望x
每秒降低 直到其为0:
if (Obstacle.activeItem == true) {
game.font.draw(game.batch, "Item active for: " + x, 100, 680);
}
我该怎么做?
我已经看到人们使用Class Timer
做类似的事情,但是我不知道这种情况下的样子。
我尝试过
int x = 10;
ScheduledExecutorService execService = Executors.newScheduledThreadPool(1);
然后
if (Obstacle.activeItem == true) {
game.font.draw(game.batch, "Item active for: " + x, 100, 680);
}
execService.scheduleAtFixedRate(new Runnable() {
public void run() {
x--;
}
}, 0L, 10L, TimeUnit.SECONDS);
但这并不能按我想要的那样工作。
答案 0 :(得分:2)
您使用libGdx标记了您的问题,所以我认为您可以使用libgdx。
为什么不使用update(float delta)
方法来减少计时器,而不是创建额外的ExecutorService?
private float timer = 10;
@Override
public void render(float delta) {
timer -= delta;
if (Obstacle.activeItem == true) {
font.draw(batch, "Item active for: " + (int)timer, 100, 680);
}
}
答案 1 :(得分:1)
以下是如何使用执行程序实现计时器类型功能的示例
public class Main {
static int x = 10;
public static void main(String[] args) {
ScheduledExecutorService execService = Executors.newScheduledThreadPool(1);
execService.scheduleAtFixedRate(() -> {
System.out.println(x);
x--;
if (x == 0)
execService.shutdownNow();
}, 1L, 1L, TimeUnit.SECONDS); //initial delay, period, time unit
}
}
强烈建议您阅读执行器。将此视为提示,并在您的用例中相应地实现。
答案 2 :(得分:0)
如果是libGdx,我为您提供了一些有效的sphagetti代码:
int reducedInt = 10;
bool isReduce = false;
float timer = 1f;
在渲染
timer -= delta;
if(timer<=0){
isReduce = true;
timer = 1;
}
if(isReduce){
reducedInt--;
isReduce = false;
}
这是经典的LibGDX sphagetti计时器代码。由于您已将其标记为LibGDX。