简体   繁体   English

Java减慢循环而不减慢程序的其余部分

[英]Java slow down for loop without slowing down rest of program

I'm creating a video game and I've got a for loop that recovers your health 我正在创建一个视频游戏,我有一个可以恢复健康的for循环

public void recoverHealth() {
    if (curHealth < finalHealth) {
        for (double i = 0; i < finalHealth; i = i + 0.1) {
            curHealth = curHealth + 0.1;
            System.out.println("health: " + curHealth);
        }
    }
}

But the problem is that java goes through this so fast it goes from 0-20 before the game even starts. 但问题是java经历了这么快,它在游戏开始前从0到20。 How can I possibly slow down the recoverHealth() method without slowing down the entire game such as Thread.sleep doesn't work.. 如何在不降低整个游戏速度的情况下减慢recoverHealth()方法,如Thread.sleep不起作用..

try {
    Thread.sleep(1000);
} catch (Exception e) {
    e.printStackTrace();
}

Any ideas? 有任何想法吗?

recoverHealth放入一个单独的线程中,并按照您的描述使用Thread.sleep()

Add this to your game program, where curHealth is accessible. 将其添加到您可以访问curHealth的游戏程序中。

timer = new Timer();
timer.schedule(new TimerTask (){
    public void run() {
        curHealth = curHealth + 0.1;
    }
}, 1000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM