Hi.
This is my first thread in this forum. First at all, sorry my bad english (read is easier than write, as can see).
Well, I'm developing a little fps 2d game (like CS2D but much simpler and very different themed).
For it, I use a MVC model and find to make a good object design.
I begin with the model development, and I finished this. Obviously this is the easiest part.
Now, I'm writing the JAVA2D presentation and my head begins to ache.
At this point is where a sync problem makes present.
I know that is one of the most common problems and there is a lot of threads in the forum about it. The alternatives I wrote are based in your help.
The only thing is there are three alternatives with similar performance but I think that where the game grow a lot, the difference will appear.
Then, I need you give me your opinions about what method y should use, and why:
* sync1
* sync2
* sync3
In all the cases, dt is in milliseconds and the main loop is something like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| while (isPlaying) { boolean modelHasChanged = false;
long currentTimestamp = Timer.getTimestamp(); timeAccumulator += currentTimestamp - lastLoopTimestamp;
while (timeAccumulator >= dt) { updateModel(dt / 1000); timeAccumulator -= dt; modelHasChanged = true; }
sync1(modelHasChanged, dt);
lastLoopTimestamp = currentTimestamp; } |
And, the view.update is something like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| public void update(...) { Graphics2D g2d = offScreenGraphics.createGraphics(); g2d.setColor(Color.black); g2d.fillRect(0, 0, width, height);
Graphics gr = bufferStrategy.getDrawGraphics(); gr.drawImage(offScreenGraphics, 0, 0, null);
gr.dispose(); g2d.dispose(); }
public void show(...) { if (!bufferStrategy.contentsLost()) bufferStrategy.show(); } |
The three sync methods are:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| private void sync1(boolean modelHasChanged, double dt) { if (modelHasChanged) { view.update(this); Thread.yield(); view.show(this); } else try { Thread.sleep(1); } catch (InterruptedException e1) {} }
private void sync2(double dt, long currentTimestamp, long ft) { view.update(this);
long desiredEnd = currentTimestamp + ft; while (Timer.getTimestamp() <= desiredEnd) try { Thread.sleep(1); } catch (InterruptedException e) {}
view.show(this); }
private void sync3(double dt) { view.update(this); Toolkit.getDefaultToolkit().sync(); Thread.yield(); view.show(this); } |
Thanks!