Kyle
Kyle

Reputation: 3

Updating a game x times per second in Java

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!

Upvotes: 0

Views: 1087

Answers (2)

Lanaru
Lanaru

Reputation: 9721

What you're looking for is called a game loop. There's a lot of documentation available concerning this. Here's a simple one:

private boolean isRunning;

public void gameLoop()
{
    while(isRunning) //the loop
    {
        doGameUpdates();
        render();
        Thread.sleep(1000); //the timing mechanism
    }
}

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.

Upvotes: 1

laobeylu
laobeylu

Reputation: 283

Maybe you should look at threads in Java: http://www.javaworld.com/jw-04-1996/jw-04-threads.html Create a new thread dedicated to repainting and handling the game loop (see the other answer).

EDIT: This tutorial may be useful: http://zetcode.com/tutorials/javagamestutorial/

Upvotes: 1

Related Questions