Me and a friend of mine are working on a game and basically, we have a hitbox set up where if our character hits it (a spider), the character loses health.
Because we are using a for loop, the inevitable happens, the player loses their health 1 by 1, but so fast the human eye can not see it. Therefore we need a timer, pause, or something for every x amount of time the player is hitting the spider. Here is our code:
if (ResetEntities.spiderObj.intersects(ResetEntities.blueCharacterObj)) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 100; i++) {
if (ResetEntities.blueHealth < 0) {
ResetEntities.blueHealth = 0;
Frame.blueHealthLabel.setText("Health: "
+ ResetEntities.blueHealth);
} else {
ResetEntities.getBlueHealth(ResetEntities.blueHealth - 1);
Frame.blueHealthLabel.setText("Health: "
+ ResetEntities.blueHealth);
}
}
}
In this code we have an if statement to check for intersection. I tried to sleep the script, (I realized 10 is incredibly fast, but 1000 lags horribly, so Thread#sleep isn't the way to go I imagine). Then we have a for statement to run 100 times (being the players health). Then we have an if seeing if the health goes below 0, set back to 0, so the player can't get negative health. If it's not below 0, we do the else and subtract 1 health. But as I said this runs too fast to see.
Any help?
The traditional way - and in my opinion best way - to do it is, to make the wounded character invulnerable until a specific point in time: When the character gets wounded, check the game-timeline (or if you dont have one then the current millis-count) then add a specific time eg 1 second (or the character-dependent recovery-time) and remember that timestamp in the character-object. A gametick that wants to wound a character first checks whether the character is still in hidden invulnerability. This is especially good because typically one doesn't really want multiple threads updating the game-state.
Use Timer for your background process' timing. And use javax.swing.SwingUtilities.invokeLater(Runnable) to update your GUI.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With