I am trying to make the game change the wave of the moles every 0.8 seconds. (My game is simply "Whack The Moles, for practicing).
My code to change waves:
double TIME = 0.8;
if (Next) { //If 0.8 seconds is up
if (Over == false) { //make sure the game hasn't ended
start = (int) (cTime/1000); //cTime is the milisecond since game started
String wave = MolesWaves.RandomWave(); //getting the new wave data
initWave(wave);
Next = false; //disallow the game from changing wave
}
}
else {
if (((cTime/1000) - start) >= TIME) { //changing speed
System.out.println("Test: " + ((cTime/1000)-start));
Next = true; //allow game to change waves
}
}
From the System.out.println("Test: " + ((cTime/1000)-start));
, this is what i get from the output log.
Test: 0.802
Test: 0.817
Test: 0.833
Test: 0.852
Test: 0.867
Test: 0.883
Test: 0.9
Test: 0.917
Test: 0.933
Test: 0.95
Test: 0.967
Test: 0.983
Test: 1.0
The problem is that the waves changes 13 times every second, it stop switching once it reached every second for a while then starts it again.
If the value of TIME
is 1
, everything is fine. The waves changes every 1 seconds.
I am using 0.8 as i am trying to implement a Difficulty selection(Easy, medium, hard...) The harder it is, the faster the wave changes.
Is the code above the culprit to my problem? If it is, please solve this for me.
We don't see the type of start
, but I'm assuming it's a double
. If so the culprit is this line:
start = (int) (cTime/1000); //cTime is the milisecond since game started
Imagine cTime
is 900 and the last wave started at time 0
(so a new wave should be starting). Then when this new wave starts, you'll set start = (int)(900/1000);
This is a truncating integer division, so the new value of start
is 0
. But this is the same as the old value -- so since nothing has changed, a new wave will start again immediately the next time the time condition is checked.
Instead of doing an integer division, convert the integer cTime to a double
and perform the division and the comparison in floating point:
start = ((double) cTime) / 1000.0;
// ...
if ((((double)cTime/1000.0) - start) >= TIME) { //changing speed
The new value of start
in the scenario above should then be 0.9
, and the new round should be allowed to last for 0.8 seconds.