I've been working on a generic 2d tile style game. Currently In my main thread I have a loop that just goes as fast as it possibly can and calls the repaint method of a JPanel that is in another class which handles the game stuff. It looks like this:
public class Main {
public static void main(String[] args) {
Island test = new Island();
while(true) {
test.getCanvas().requestFocus();
test.getCanvas().repaint();
}
}
}
getCanvas() just returns the JPanel.
Currently this has done what I've wanted, now that I've started adding movement for a player and obviously I don't want to move him across the screen as fast as I possibly can. So I have an input map and action map in my Island class and that detects the key presses and releases and tells my player class which keys are being held. I then move my player about inside the player class with a swing timer that calls every 10ms. So I guess this is like my game tick, my game will make frames as fast as it possibly can and then the game does all its logic stuff 100 times a second, I will be adding more to the gamelogic of course, not just movement.
After doing some research it would appear a swing timer isn't the best way of doing this as it is designed for doing small tasks and for swing tasks. So I guess my question is, is it sensible to make my frames the way I am in my main method, and what would be a good way of getting my game to tick reliably every 10ms or whatever? I've had a few ideas, like maybe I should make a new thread that handles the game logic and use the System.getnanotime or whatever its called to measure the time taken to do a tick and then do a wee thread.sleep for however long it is until we reach 10ms and then repeat.
I am happy to post more code if you want :), and thanks in advance.
A standard way of doing this is in a Thread. Heres a standard game barebones game thread
Note you will need to call gameThead.start() to start your game!
Creating a good (windowed app) gameloop without eating CPU 100% is actually a very tricky task. Sidescroll animating a sprite with constant speed easily introduces jerkiness if there is one to be seen.
After running several ideas this is what found best, sidescrolling is most of the time butter smooth. VSYNCing is something what may work good in a windowed mode or not, I've found varying results on different machines and OSses.
Test app is not using SwingUI because most games don't need it anyway. Gameloop is an active update-render loop without external threads making things easier to program. Use keyPressed callback to update firePressed=true and etc flag variables and use values in a loop.
Run test app c:> java -cp ./classes GameLoop2 "fullscreen=false" "fps=60" "vsync=true"
Gameloop logic may look crazy but believe me this works suprisingly well. Give it a run. edit: Running TaskManager at the same time creates jerkiness in a smooth animation I guess updating instrumentation statistics gives a heavy hit.