Hi !
Featured games (84)
games approved by the League of Dukes
Games in Showcase (549)
Games in Android Showcase (135)
games submitted by our members
Games in WIP (593)
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 3398 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;

 * - A smooth scrolling game loop.
 * @author Mario Gianota
public class Main implements KeyListener {
    * Colour palette
    private static Color[] COLORS = new Color[] {,,, Color.white,,
        Color.yellow, Color.gray, Color.cyan,, Color.lightGray,
        Color.magenta,, 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.setSize(640, 480);
            // 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();
                // Update rectangle co'ords
                if( rect.x > mainFrame.getWidth() )
                    rect.x = -rect.width;
                // Draw
                Graphics g = bufferStrategy.getDrawGraphics();
                // Flip the buffer
                if( ! bufferStrategy.contentsLost() )

                // 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) {
        } finally {
    private void drawScreen(Graphics g) {
        g.fillRect(0, 0, 640, 480);
        g.drawString("FPS: "+ fps, 0, 17);
        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;
    public void keyPressed(KeyEvent e) {
        if( e.getKeyCode() == KeyEvent.VK_ESCAPE ) {
    public void keyReleased(KeyEvent e) {
    public void keyTyped(KeyEvent e) {
    public static void main(String[] args) {
        try {
            GraphicsEnvironment env = GraphicsEnvironment.
            GraphicsDevice device = env.getDefaultScreenDevice();
            Main test = new Main(device);
        } catch (Exception e) {

Have fun.

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.

Offline whome

Junior Devvie

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.
                // 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)
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.

Robo11 (15 views)
2015-01-25 06:14:26

basil_ (26 views)
2015-01-17 22:29:32

wxwsk8er (22 views)
2015-01-16 21:42:21

wxwsk8er (20 views)
2015-01-16 20:44:20

basil_ (25 views)
2015-01-14 09:46:59

basil_ (21 views)
2015-01-14 09:46:52

wxwsk8er (32 views)
2015-01-13 20:42:16

wxwsk8er (34 views)
2015-01-13 03:23:59

vctt (54 views)
2015-01-12 03:21:07

wxwsk8er (31 views)
2015-01-12 03:11:59
2D Dynamic Lighting
by ThePixelPony
2015-01-01 20:25:42

How do I start Java Game Development?
by gouessej
2014-12-27 19:41:21

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 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‑
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!