Calling function according to system time
I'm having trouble with calling function according to system time correctly. My main purpose is to provide a better movement effect to my "Bomberman" object. Unfortunately, it behaves weird. I believe that there is a stupid little mistake, but I can't find due to sleepless 30 hours. Here is my code:
if (System.currentTimeMillis() % 600 <= 200) {
if (!gEngine.gMap.bomber.isImmune) {
gEngine.gMap.bomber.setImage("bomberman_up3.gif");
} else {
gEngine.gMap.bomber.setImage("bomberman_red_up3.gif");
}
} else if (System.currentTimeMillis() % 600 <= 400) {
if (!gEngine.gMap.bomber.isImmune) {
gEngine.gMap.bomber.setImage("bomberman_up2.gif");
} else {
gEngine.gMap.bomber.setImage("bomberman_red_up2.gif");
}
} else if (System.currentTimeMillis() % 600 >= 400)
{
if (!gEngine.gMap.bomber.isImmune) {
gEngine.gMap.bomber.setImage("bomberman_up1.gif");
} else {
gEngine.gMap.bomber.setImage("bomberman_red_up1.gif");
}
}
By the way, I'm pretty sure that the weirdness is not about 开发者_JS百科the order of gif images. Code should change image 3 times per second. Maybe I can sleep if you help me. :)
Thanks in advance.
Assuming you are calling the function periodically with a timer, your particular problem appears to be that you are requesting the system time many times, rather than once, so the value you are testing in the three parts changes.
You would be better off creating a queue of elements to draw on a given update time, as your code will end up more and more complicated if you just use lots of if
statements rather than OO abstractions.
When the screen is painted, get the time once, and pass that time to all the elements to be drawn. That way, all the elements will be in synch with each other, and you don't have problems with the time at the first if
being different from the time at the third if
.
So I'd have BomberMan implement an interface with a draw ( Graphics2D g, long time )
method which all animated elements implement, and have get and set methods instead of a public isImmune field. The get and set methods change the value of an array of images for the sprite, so the code doesn't need to know about any other state the bomber man is in.
精彩评论