Java-Gaming.org Hi !
Featured games (83)
games approved by the League of Dukes
Games in Showcase (539)
Games in Android Showcase (132)
games submitted by our members
Games in WIP (603)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Game Loop question: Which way is better?  (Read 2547 times)
0 Members and 1 Guest are viewing this topic.
Offline Z-Man
« Posted 2011-03-03 03:31:54 »

So, I have been doing a little Java Game programming for fun and I have seen two maybe three ways to do the game loop. I was just wondering if one is better then the other and why. So the first way and the way I currently do it is using javax.swing.Timer and a custom action listener. The second way I have seen is just a Thread using System.getTimeMillis() to get the timing, and the final one is the same as the second but using sleep() instead of System.getTimeMillis().
Offline ShannonSmith
« Reply #1 - Posted 2011-03-03 03:51:09 »

It depends a lot on what type of game you are doing

1) javax.swing.Timer - for lightweight games where the timer routine is very quick also if you want to use a swing gui and not have to worry about threading issues.
2) Fixed sleep time, measure game time with System.nanoTime() - the best option for smooth animation, don't use currentTimeMillis() it is way less granular on some platforms.
3) Fixed time step with a sleep for remainder - sleep generally has pretty low granularity worse for smooth animation but a fixed timestep can have quite a few advantages (stable/repeatable).



Offline BatKid

Senior Newbie





« Reply #2 - Posted 2011-03-03 06:04:08 »

If you use a fixed sleep time (option 2), you may need to worry about interpolation as the execution time for each step may be different.   For a simple game, I would go with fix time-step (option 3).

Learn Java in 3D with env3d
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline dishmoth
« Reply #3 - Posted 2011-03-03 09:09:08 »

If the JGO Wiki ever reappears, this would be a good topic to get nailed down once and for all.

Offline luisoft

JGO Coder


Projects: 6


Java games rock!


« Reply #4 - Posted 2011-03-03 12:47:58 »

do you have any templates for option 2 and 3?
Offline IronclawsBt

Junior Devvie


Medals: 1



« Reply #5 - Posted 2011-03-03 15:11:13 »

I wrote a tutorial on game loops on my website. Here's the source code if that's all your interested in. I need to do a little bit of fix up (I shouldn't have used doubles to represent the time in seconds), but it should work.

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  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
public abstract class GameLoop
{
    private boolean runFlag = false;
 
    /**
     * Begin the game loop
     * @param delta time between logic updates (in seconds)
     */

    public void run(double delta)
    {
        runFlag = true;
 
        startup();
        // convert the time to seconds
        double nextTime = (double)System.nanoTime() / 1000000000.0;
        double maxTimeDiff = 0.5;
        int skippedFrames = 1;
        int maxSkippedFrames = 5;
        while(runFlag)
        {
            // convert the time to seconds
            double currTime = (double)System.nanoTime() / 1000000000.0;
            if((currTime - nextTime) > maxTimeDiff) nextTime = currTime;
            if(currTime >= nextTime)
            {
                // assign the time for the next update
                nextTime += delta;
                update();
                if((currTime < nextTime) || (skippedFrames > maxSkippedFrames))
                {
                    draw();
                    skippedFrames = 1;
                }
                else
                {
                    skippedFrames++;
                }
            }
            else
            {
                // calculate the time to sleep
                int sleepTime = (int)(1000.0 * (nextTime - currTime));
                // sanity check
                if(sleepTime > 0)
                {
                    // sleep until the next update
                    try
                    {
                        Thread.sleep(sleepTime);
                    }
                    catch(InterruptedException e)
                    {
                        // do nothing
                    }
                }
            }
        }
        shutdown();
    }
 
    public void stop()
    {
        runFlag = false;
    }
 
    public abstract void startup();
    public abstract void shutdown();
    public abstract void update();
    public abstract void draw();
}

It's not what you know, it's what other people think you know.
Just hope you don't get quizzed on it.
Game engine design tutorials
Offline aazimon
« Reply #6 - Posted 2011-03-03 22:45:28 »

Andrew Davison covers this in his book "killer game programming", You can download the source he has for various timers here http://fivedots.coe.psu.ac.th/~ad/jg/ch1/index.html
Offline fletchergames

Senior Devvie





« Reply #7 - Posted 2011-03-04 04:07:26 »

Andrew Davison covers this in his book "killer game programming", You can download the source he has for various timers here http://fivedots.coe.psu.ac.th/~ad/jg/ch1/index.html
I had some weird problems using the game loop code from that book, though I admit that I did make a couple of small changes to it.  The problems were only a significant issue on older computers, so it took me years to figure out what caused it.  I deleted the portion of my game loop that was from Killer Game Programming in Java, and my code suddenly started working.
Offline aazimon
« Reply #8 - Posted 2011-03-04 17:45:05 »

I use that loop now, with some changes. I'm curious what your game loop looks like now. Can you share it?
Offline fletchergames

Senior Devvie





« Reply #9 - Posted 2011-03-04 21:21:36 »

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  
protected final void runSafely() {
   //verify that the loop will continue
   shouldContinueLoop = true;
   
   //This variable is used for computing the length of an update phase.
   long lastUpdatePhase = Time.currentTimeMillis();

   while(shouldContinueLoop) {
      //if the application isn't active, sleep for half a second
      if(!isApplicationActive()) {
         try {
            Thread.sleep(500);
         } catch(InterruptedException exception) {}
           
         continue;
      } //end if the frame isn't active
     
      //figure out the start of the current phase
      long currentCycle = Time.currentTimeMillis();
      long updatePhaseLength = currentCycle - lastUpdatePhase;
      if(updatePhaseLength > maximumUpdateLength)
         updatePhaseLength = maximumUpdateLength;
     
      //update the current model
      doUpdatePhase(updatePhaseLength);
      lastUpdatePhase = currentCycle;
   
      //render the game
      render();
     
      //yield to other threads
      Thread.yield();
   } //end while forever
} //end runSafely


I was just talking about this at http://www.java-gaming.org/topics/simple-game-loop/23831/msg/198753/view.html#msg198753.  I added the Thread.yield because of what they said, though it doesn't seem to change anything.  My current code doesn't have any of the sleeping and oversleeping stuff from Killer Game Programming in Java.
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline aazimon
« Reply #10 - Posted 2011-03-04 23:42:02 »

I haven't had any trouble with the Killer Game loop, but I haven't run it on an older computer. I will have to look at this more.
Offline fletchergames

Senior Devvie





« Reply #11 - Posted 2011-03-07 13:43:41 »

In all fairness, I did screw around with the Killer Game loop slightly.  It's supposed to have an update phase that always uses a constant time period, but I made mine use a variable time period.  I was losing time when the timer was too granular because it would still sleep or yield or whatever.
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

rwatson462 (30 views)
2014-12-15 09:26:44

Mr.CodeIt (23 views)
2014-12-14 19:50:38

BurntPizza (50 views)
2014-12-09 22:41:13

BurntPizza (84 views)
2014-12-08 04:46:31

JscottyBieshaar (45 views)
2014-12-05 12:39:02

SHC (59 views)
2014-12-03 16:27:13

CopyableCougar4 (57 views)
2014-11-29 21:32:03

toopeicgaming1999 (123 views)
2014-11-26 15:22:04

toopeicgaming1999 (114 views)
2014-11-26 15:20:36

toopeicgaming1999 (32 views)
2014-11-26 15:20:08
Resources for WIP games
by kpars
2014-12-18 10:26:14

Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!