I’m a bit new to game programming and I’ve decided to do a little experiment in Java. I’m using the Swing/AWT api to implement a game by drawing on a JPanel. However, I’m unsure as to how to implement “passing time” in the game. Does anyone have any ideas on this?
Thanks!
What you’re looking for is called a game loop. There’s a lot of documentation available concerning this. Here’s a simple one:
The idea is that the code inside a while loop is executed over and over, and will sleep for 1 second between execution. This is a way of implementing the “passing of time”. For example, if you have an object with a X position, and in the while loop you put
object.X += 1, the object’s X position will advance by 1 for every iteration of the loop, that is 1 per second.This is a very basic game loop and it has some problems, but it will do if you’re a beginner. Once you become a bit more experienced, look up variable and fixed timestep game loops.
However, you’ll have to run this code in a separate thread so that the display will actually get updated.