Timing issues while animating

Hello,

I'm writing a simple animation routine, and experienced a funny problem when running this on a windows-based machine.

What I'm trying to do is pretty simple and looks like this in the main animation thread.....

// Main animation loop...

while(animationThread !=null)

{

startTime = System.currentTimeMillis();

// Code to create next frame goes here...

....

// Done drawing this frame, so now repaint the viewport

// (Uses double buffering)

viewport.repaint();

try{

executionTime = System.currentTimeMillis() - startTime;

System.out.println(executionTime);

Thread.sleep(Math.max(33 - executionTime, 0));

}catch (InterruptedException e){}

}

So basically, at the beginning of every iteration, I get the system time in millisecs, do what I need to do to construct the next frame of animation, issue a repaint() to tell AWT to draw the component (Basically, a Canvas) , then use the system time again to compute the execution time. Then, I sleep for 33 minus execution time (Hoping for a constant 33 ms between each frame, i.e. 30 FPS). In most frames (based on the output of the println statement every frame), I see the execution time is 0 millisecs (so it's negligible). So that means the thread must sleep for 33 ms between frames.

However, on my machine here, when I execute this piece of code, I get a rather jerky animation, with some frame coming up faster, and some coming up slower.

When I changed this to 30 ms instead of 33 ms, everything seems to work perfectly. No jerks what-so-ever !!! I've noticed animation is smooth when I use sleep periods of multiples of 10 ms, but is jerky when I use sleep periods that are not multiples of 10 ms.

Is it an issue with windows that it's task scheduler or whatever is not able to cope with sleep periods which are not in multiples of 10 ms?

At present, I'm happy with the sleep time of 30, but I'm still curious to know why this happens.

Thanks,

Hamy

[2480 byte] By [HamyTheVeggya] at [2007-11-26 15:58:15]
# 1

Hello Hamy,

You probably might want to look at timing framework (https://timingframework.dev.java.net) that created to help developers with witting animated stuff. Also, here is one more project that deals with animation (actually, it's based on timing framework) https://mediajuggler.dev.java.net

Best Regards,

Alexey

AlexeyUshakova at 2007-7-8 22:19:17 > top of Java-index,Security,Cryptography...
# 2
Thanks Alexey,The articles on timing framework did help.Best regards,Hamy
HamyTheVeggya at 2007-7-8 22:19:18 > top of Java-index,Security,Cryptography...