如果你的人正在挨饿,我有一个计时器可以减去一个健康点,如果他正在挨饿,我希望它每10秒减去一个点,但是一旦计时器启动它循环就会消除健康,我做了什么错误?
http://puu.sh/vAu2H.png这是显示结果的输出。它会在10秒甚至完成之前消除健康。
这是我的计时器代码:
`
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.util.Timer;
import java.util.TimerTask;
public class GUI {
public void tick() {
if(Player.starving) {
Timer timer = new Timer();
int begin = 0; //timer starts after 1 second.
int timeinterval = 10 * 1000; //timer executes every 10 seconds.
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
//This code is executed at every interval defined by timeinterval (eg 10 seconds)
//And starts after x milliseconds defined by begin.
Player.health = Player.health - 1;
System.out.println(Player.health);
}
},begin, timeinterval);
}
}
public void render(Graphics g) {
Font menuFont = new Font( "SansSerif", Font.PLAIN, 18);
g.setFont(menuFont);
g.setColor(Color.green);
g.drawString("Money: " + String.valueOf(Player.money) + " $", 655, 25);
g.setColor(Color.red);
g.drawString("Health: " + String.valueOf(Player.health) + " / 5.0", 10, 25);
g.setColor(Color.white);
g.drawString(String.valueOf(Time.globalTime), Engine.WIDTH * Engine.SCALE / 2 + 30, 25);
if(Player.health <= 0) {
g.setColor(Color.black);
g.fillRect(0, 0, Engine.WIDTH, Engine.HEIGHT);
g.setColor(Color.white);
g.drawString("Your pet is dead :'(", Engine.WIDTH * Engine.SCALE / 2 - 75, Engine.HEIGHT * Engine.SCALE / 2);
}
tick();
}
}
以下是我获得的视频:https://www.youtube.com/watch?v=x3JwZh_rpqc&feature=youtu.be
答案 0 :(得分:1)
每次调用渲染时,您都会启动一个关闭健康的新计时器。你需要确定一个计时器是否已经启动,你不会启动另一个计时器。