Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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. How can I possibly slow down the recoverHealth() method without slowing down the entire game such as Thread.sleep doesn't work..

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

Any ideas?

like image 584
Bryce Hahn Avatar asked Jun 20 '26 04:06

Bryce Hahn


1 Answers

Put recoverHealth into a separate thread, and use Thread.sleep() as you describe.

like image 76
merlin2011 Avatar answered Jun 21 '26 17:06

merlin2011