The Java2D engine I'm building uses a render loop that iterates over a Set of Renderable objects. It calls render(RenderControl) on each Renderable object. It's then up to each object to call render(int,int,int,int,int[]) so that the image data is added into the main BufferedImage's raster.

In a test object that just renders an image on screen and increments the position based on how much time has passed (to animate it), I have this code:

Where img is a BufferedImage representing the image loaded previously using ImageIO.read.

When this runs, however, the moving image kind of chugs in it's movement. It freezes or relapses in its path around every second, even though the frame rate is consistently 55-60fps (capped using Thread.sleep).

Is there something wrong with the way I'm doing this? Should the position changing code be executed in a separate thread?

Calling System.currentTimeMillis() every time you want to want to update the last function causes leaks for two reasons.

1) When you call it in the "if" clause, it'll get a time let's say (10 millisecs). Then, when you call it again at "last" it'll then read (13 millisecs). You have just lost a few milliseconds of time because of the small difference of the 2 calls.

2) System.currentTimeMillis() is not an 100% reliable call and suffers from OS slowdowns. If you call the function and your program stutters at the sleep() function, the time will be way off.

By using "last -= 20", it makes sure that even if the time stutters, you will not be losing any frames of time in the game. It also guarantees that there is only one time call per update cycle, and that prevents time leaks entirely.

java-gaming.org is not responsible for the content posted by its members, including references to external websites,
and other references that may or may not have a relation with our primarily
gaming and game production oriented community.
inquiries and complaints can be sent via email to the info‑account of the
company managing the website of java‑gaming.org