Sometimes when I play my sidescroller, I move at the normal speed. However, other times my character moves very slow. The code never changes at all, so I think this currentTimeMillis method is at fault. Can anyone explain why I sometimes move very slowly and other times faster? Thanks.
public void run(){ // run method for animation
beforeTime = System.currentTimeMillis();
while(animationDone == false){
jumpCycle();
timeDifference = System.currentTimeMillis() - beforeTime;
sleepTime = 4 - timeDifference;
if(sleepTime < 0)
sleepTime = 2;
try{
Thread.sleep(sleepTime);
}
catch(Exception e){
}
beforeTime = System.currentTimeMillis();
}
isJumping = isFalling = animationDone = false;
}
Edit: For anyone with the same problem, I ended up just using java.util.Timer and java.util.TimerTask to accomplish this with platform independent precision.
The inherent problem in your animation code is that you’re relying on the passage of time to do the animation correctly. On any computer system this is impossible, due to thread scheduling.
The way computer games solve this problem is by changing the amount of animation done according to the amount of time that passed since the last draw. That way, regardless of your frame-rate, the animation speed will not change.