gpt4 book ai didi

java - Java 每秒将 int 从 10 减少到 0

转载 作者:行者123 更新时间:2023-12-01 19:43:51 25 4
gpt4 key购买 nike

我定义一个

int x = 10;

现在我希望x每秒减少直到0:

if (Obstacle.activeItem == true) {
game.font.draw(game.batch, "Item active for: " + x, 100, 680);
}

我怎样才能做到这一点?

我见过人们使用类计时器做类似的事情,但我不知道在这种情况下它应该是什么样子。

我试过了

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);

但这并没有达到我想要的效果。

最佳答案

您用 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);
}
}

关于java - Java 每秒将 int 从 10 减少到 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54325354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com