Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (494)
Games in Android Showcase (114)
games submitted by our members
Games in WIP (563)
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  
  Constant Animation Speeds  (Read 1729 times)
0 Members and 1 Guest are viewing this topic.
Offline PertBanking

Innocent Bystander





« Posted 2013-05-22 21:28:37 »

Hello all,

I'm new here, so I apologize in advance if this is irrelevant or obviously answered in another thread.   Undecided

I've been working on a 2D gravity simulator, and I've found that when I run the code on my laptop (which is reasonably fast), it goes at the speed that I want it to.  However, when I run the code on my PC (which is slow), I find that it goes at about half the speed that I want it to. 

The physics for the game is done inside the paint() method of JComponent, which is indirectly called by javax.swing.Timer every 10 milliseconds. 

My question is this:  Is there any way to animate with Graphics2D so that the animation speed is constant, no matter how fast the computer is?  Or, if I'm using the wrong classes for animation, what is a good alternative for what I'm trying to do?
Offline notk0

Senior Newbie





« Reply #1 - Posted 2013-05-22 21:42:52 »

You update your simulation a number of times per second, and draw in the remaining time, if drawing takes too much time you compensate by skipping drawing and updating less.
Search on how to write a good game loop.
Offline philfrei
« Reply #2 - Posted 2013-05-23 00:09:59 »

The util.timer has been shown to be a better choice than the swing.timer. Chapter two of "Killer Game Programming" compares the two. This chapter also has some good discussion on game loops that don't use timers.

The big issue with the swing.timer is that everything it does is queued onto the Event Dispatch Thread. This thread can get kind of backed up if there is too much going on. The utility timer creates new threads.

Another issue is that many Microsoft OS setups will only resolve to about 15 or 16 msecs. Thread.sleep(), scheduling for the timer, and System.currentTimeMillis() all suffer from this. System.nanoTime(), in contrast, uses the JVM's "high resolution time source". In any event, scheduling the events for every 10ms is kind of problematic. Something more on the range of 60fps is more reasonable (16.6 milliseconds) in terms of fitting with the OS's that I know about anyway.

A "newish" class might even be a better choice than the utility timer: [quote from API follows] "ScheduledThreadPoolExecutor which is a thread pool for repeatedly executing tasks at a given rate or delay. It is effectively a more versatile replacement for the Timer/TimerTask combination, as it allows multiple service threads, accepts various time units, and doesn't require subclassing TimerTask (just implement Runnable). Configuring ScheduledThreadPoolExecutor with one thread makes it equivalent to Timer."

You can set it to recur at the exact interval rather than at a delta interval. Utility timer has this too: use the method sheduleAtFixedRate() instead of schedule().

I would put the physics in its own method. I would have the timer or game loop call an "update()" for the physics and a "render()" for the draw, as two commands. In this case, the render() might only consist of a repaint() for the JComponent being used for the display.

If I recall correctly there's been some discussion that one should prefer to overwrite paintComponent() instead of paint(). I think there are notes in the API that explain why. It might not matter in your case. I don't know.

"Greetings my friends! We are all interested in the future, for that is where you and I are going to spend the rest of our lives!" -- The Amazing Criswell
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline gimbal

JGO Knight


Medals: 25



« Reply #3 - Posted 2013-05-31 12:11:42 »

The utility timer creates new threads.

Huh?

I quote from the javadoc:

"Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks, sequentially"
Offline philfrei
« Reply #4 - Posted 2013-05-31 18:24:41 »

Thanks for the correction.

"Greetings my friends! We are all interested in the future, for that is where you and I are going to spend the rest of our lives!" -- The Amazing Criswell
Offline CyberAxe

Junior Newbie





« Reply #5 - Posted 2013-06-29 16:39:48 »

I do speed in ticks

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  
  @Override
  public void run() {
    long timeNow;
    long lastTime = System.nanoTime();

    final double nsPerTick = 1000000000D / 60D;   // 1 Billion Double

    double delta = 0;

    while (running) {
      timeNow = System.nanoTime();
      delta += (timeNow - lastTime) / nsPerTick;
      lastTime = timeNow;

      // Throttle FPS
     while (delta >= 1) {
        shouldTick = true;
        ticks++;
        tick();
        delta -= 1;
      }
     
      try {
        Thread.sleep(2);
      } catch (InterruptedException ex) {
        Logger.getLogger(Game.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
      }

      render();

      if (tickTime - lastTimeMillis >= 1000) { // One Second has Passed
       lastTimeMillis = tickTime;
       }
    }
 
    stop();
  }


The above example does 60 ticks per second which is easily changeable (just change the nsPerTick "/ 60D" value) and no limit on rendering frames
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.

Dwinin (19 views)
2014-09-12 09:08:26

Norakomi (54 views)
2014-09-10 13:57:51

TehJavaDev (63 views)
2014-09-10 06:39:09

Tekkerue (31 views)
2014-09-09 02:24:56

mitcheeb (53 views)
2014-09-08 06:06:29

BurntPizza (37 views)
2014-09-07 01:13:42

Longarmx (23 views)
2014-09-07 01:12:14

Longarmx (27 views)
2014-09-07 01:11:22

Longarmx (26 views)
2014-09-07 01:10:19

mitcheeb (34 views)
2014-09-04 23:08:59
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

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
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!