Okey, so I’m messing around trying to get the best draw method timing out of my gameloop and I found something that I don’t quite understand.
Keep in mind this is only a test, not the final code. I’m trying to tweak what I can before starting a real project, so maybe some things are kind of sloppy right now.
This is my main gameloop in Start.class:
@Override
public void run(){
final int SKIP_TICKS = 1000000000 / FPS;
final int MAX_FRAMESKIP = 5;
int loops = 0;
double before = System.nanoTime();
while(isRunning){
loops = 0;
ScreenState state = window.getCurrentState();
double now = System.nanoTime();
while( now - before > SKIP_TICKS && loops < MAX_FRAMESKIP) {
state.run();
before += SKIP_TICKS;
loops++;
}
//window.render();
window.repaint();
double lastRenderTime = now;
while ( now - lastRenderTime < SKIP_TICKS && now - before < SKIP_TICKS)
{
Thread.yield();
try {Thread.sleep(1);} catch(Exception e) {}
now = System.nanoTime();
}
}
}
This is the render and paint method in my Screen.class:
@Override
public void paint(Graphics g) {
do {
// The following loop ensures that the contents of the drawing buffer
// are consistent in case the underlying surface was recreated
do {
// Get a new graphics context every time through the loop
// to make sure the strategy is validated
Graphics g2 = strategy.getDrawGraphics();
// Render to graphics
// currentstate.paintComponents(g);
currentstate.draw(g2);
// Dispose the graphics
g2.dispose();
// Repeat the rendering if the drawing buffer contents
// were restored
} while (strategy.contentsRestored());
// Display the buffer
strategy.show();
// Repeat the rendering if the drawing buffer was lost
} while (strategy.contentsLost());
}
public void render(){
do {
// The following loop ensures that the contents of the drawing buffer
// are consistent in case the underlying surface was recreated
do {
// Get a new graphics context every time through the loop
// to make sure the strategy is validated
Graphics g = strategy.getDrawGraphics();
// Render to graphics
// currentstate.paintComponents(g);
currentstate.draw(g);
// Dispose the graphics
g.dispose();
// Repeat the rendering if the drawing buffer contents
// were restored
} while (strategy.contentsRestored());
// Display the buffer
strategy.show();
// Repeat the rendering if the drawing buffer was lost
} while (strategy.contentsLost());
}
So I execute this in either:
public void draw(Graphics g){
if(!genDone) return;
start = System.currentTimeMillis();
g.setColor(Color.red);
g.fillRect(0, 0, Screen.getInstance().getWidth(), Screen.getInstance().getHeight());
for(Tile t : tiles)
g.drawImage(t.img.getImage(), t.x+trackX, t.y+trackY, null);
System.out.println("Draw: " + (System.currentTimeMillis() - start));
}
if i run the code from paint(Graphics g) i get:
20 iterations: 121
20 iterations: 298
20 iterations: 131
Now, if I run the sme code from render(Graphics g):
20 iterations: 296
20 iterations: 297
20 iterations: 280
Why is there that kind of difference?