Java-Gaming.org Hi !
Featured games (83)
games approved by the League of Dukes
Games in Showcase (512)
Games in Android Showcase (119)
games submitted by our members
Games in WIP (576)
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  
  Smooth scroll  (Read 3294 times)
0 Members and 1 Guest are viewing this topic.
Offline mgianota

Senior Newbie





« Posted 2010-03-27 10:51:57 »

Thought I'd share the code for my smooth scrolling game loop:



import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import java.awt.event.KeyListener;

/**
 * Main.java - A smooth scrolling game loop.
 *
 * @author Mario Gianota
 */
public class Main implements KeyListener {
   /*
    * Colour palette
    */
    private static Color[] COLORS = new Color[] {
        Color.red, Color.blue, Color.green, Color.white, Color.black,
        Color.yellow, Color.gray, Color.cyan, Color.pink, Color.lightGray,
        Color.magenta, Color.orange, Color.darkGray };
   
    Frame mainFrame;
    long lastTime;
    int fps;
    int frameCounter;
    long elapsedTime;
    long delayTime = 0;
    Rectangle rect;
   
    public Main(GraphicsDevice device) {
        try {
            // Setup the frame
            GraphicsConfiguration gc = device.getDefaultConfiguration();
           
            mainFrame = new Frame(gc);
            mainFrame.setUndecorated(true);
            mainFrame.setIgnoreRepaint(true);
            mainFrame.setVisible(true);
            mainFrame.setSize(640, 480);
            mainFrame.setLocationRelativeTo(null);
            mainFrame.createBufferStrategy(3);
            mainFrame.addKeyListener(this);
           
            // Cache the buffer strategy and create a rectangle to move
            BufferStrategy bufferStrategy = mainFrame.getBufferStrategy();
            rect = new Rectangle(0, 100, 50, 50);
           
            // Main loop

            while(true) {
                long time = System.nanoTime();
                calculateFramesPerSecond();
               
                // Update rectangle co'ords
                rect.x+=4;
               
                if( rect.x > mainFrame.getWidth() )
                    rect.x = -rect.width;
               
                // Draw
                Graphics g = bufferStrategy.getDrawGraphics();
                drawScreen(g);
                g.dispose();
               
                // Flip the buffer
                if( ! bufferStrategy.contentsLost() )
                    bufferStrategy.show();

                // Delay for a period of time equal to 1/60th of a
                // second minus the elapsed time
                elapsedTime = System.nanoTime() - time;
                delayTime = 1000000000L/60 - elapsedTime;
                time = System.nanoTime();
                while( System.nanoTime() - time <= delayTime)
                    ;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            device.setFullScreenWindow(null);
        }
       
    }
    private void drawScreen(Graphics g) {
        g.setColor(COLORS[1]);
        g.fillRect(0, 0, 640, 480);
        g.setColor(COLORS[3]);
        g.drawString("FPS: "+ fps, 0, 17);
        g.setColor(COLORS[0]);
        g.fillRect(rect.x, rect.y, rect.width, rect.height);
    }
    private void calculateFramesPerSecond() {
        long time = System.nanoTime();
        if( time - lastTime >= 1000000000L ) {
            fps = frameCounter;
            lastTime = time;
            frameCounter = 0;
        }
        frameCounter++;
    }
    public void keyPressed(KeyEvent e) {
        if( e.getKeyCode() == KeyEvent.VK_ESCAPE ) {
            System.exit(0);
        }
    }
    public void keyReleased(KeyEvent e) {
       
    }
    public void keyTyped(KeyEvent e) {
       
    }
    public static void main(String[] args) {
        try {
            GraphicsEnvironment env = GraphicsEnvironment.
                getLocalGraphicsEnvironment();
            GraphicsDevice device = env.getDefaultScreenDevice();
            Main test = new Main(device);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


Have fun.

--Mario
Offline DzzD
« Reply #1 - Posted 2010-03-27 14:09:16 »

NB: there is a better place to post shared code : Shared Code Board

Offline h3ckboy

JGO Coder


Medals: 5



« Reply #2 - Posted 2010-03-27 19:46:27 »

u could also make a tutorial Smiley. I think there is a tutorial board
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline mgianota

Senior Newbie





« Reply #3 - Posted 2010-03-27 21:16:33 »

A tutorial!? I'd have to go back to square one, fifteen years ago sitting in a comp sci. computer room drumming my fingers on the desk waiting for the download link for The Java Programming Language to appear.  Cheesy

Believe it or not, the smooth scroll code above is very nearly fifteen years old. Because of it's age it is extremely reliable. The most recent change was made when Javasofct released the system nanotimer. But since then the code has remained largely unchanged.

IMO the best tutorials are those that just show the code interspersed with a few comments. I never read most of the verbiage on the Java tutorial site, I normally go straiight for the section of code I am interested in and copy and paste the chunk into whatever piece of software I happen to be working on.

Oh, just one rather big thing to point out about the smooth scroll code: I've never written a full game in Java and released it so feel free to shoot me down in flames.

--Mario
Offline whome

Junior Duke




Carte Noir Java


« Reply #4 - Posted 2010-03-30 01:31:18 »

Thought I'd share the code for my smooth scrolling game loop:

We had a similar topic last year, evaluating few gameloops. What I prefer is a game loop that does not eat 100% CPU. After all most java games a small "flash" games so should behave well.


I run a test through your code, but added Thread.sleep(10) to yield a cpu. Animation was still quite good.
Quote
                // Delay for a period of time equal to 1/60th of a
                // second minus the elapsed time
      Thread.sleep(10);
                elapsedTime = System.nanoTime() - time;
                delayTime = 1000000000L/60 - elapsedTime;
                time = System.nanoTime();
                while( System.nanoTime() - time <= delayTime)
                    ;
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.

Longarmx (50 views)
2014-10-17 03:59:02

Norakomi (39 views)
2014-10-16 15:22:06

Norakomi (31 views)
2014-10-16 15:20:20

lcass (35 views)
2014-10-15 16:18:58

TehJavaDev (66 views)
2014-10-14 00:39:48

TehJavaDev (65 views)
2014-10-14 00:35:47

TehJavaDev (55 views)
2014-10-14 00:32:37

BurntPizza (72 views)
2014-10-11 23:24:42

BurntPizza (43 views)
2014-10-11 23:10:45

BurntPizza (84 views)
2014-10-11 22:30:10
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

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06
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!