Hi,
I'm new to Java game programming. I read a lot on how to implement a game loop, but I can't quite get it to be smooth. I've look all over the forums and the net and I think I've implemented this correctly, but the thing still jitters or stutters. Here's my test code. It's a very simple game loop.
If you run this, you will see the red box somewhat stutter when moving.
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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| import java.awt.Color; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.image.BufferStrategy; import javax.swing.JFrame;
public class CTest implements Runnable {
static final int APP_WIDTH = 640; static final int APP_HEIGHT = 480;
private GraphicsEnvironment mGraphicsEnv = null; private GraphicsDevice mGraphicsDev = null; private GraphicsConfiguration mGraphicsConf = null; private BufferStrategy mBufferStrategy = null;
private JFrame mFrame = null;
private Graphics2D mGraphics = null;
private long mStart = 0; private long mEnd = 0; private long mDT; private double mSeconds;
private long mSetFPS = (1000/60) * 1000000;
private int mBoxX = 200; private int mBoxY = 200; private int mBoxDX = 1; private int mBoxDY = 1;
CTest() { mGraphicsEnv = GraphicsEnvironment.getLocalGraphicsEnvironment(); mGraphicsDev = mGraphicsEnv.getDefaultScreenDevice(); mGraphicsConf = mGraphicsDev.getDefaultConfiguration();
mFrame = new JFrame(mGraphicsConf); mFrame.setIgnoreRepaint(true); mFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mFrame.setLocation(100, 100); mFrame.setSize(APP_WIDTH, APP_HEIGHT); mFrame.setFocusTraversalKeysEnabled(false); mFrame.setResizable(false); mFrame.setVisible(true);
mFrame.createBufferStrategy(2); mBufferStrategy = mFrame.getBufferStrategy();
Thread thread = new Thread(this); thread.start(); }
public void run() { while(true) { mStart = System.nanoTime();
mBoxX += mBoxDX; mBoxY += mBoxDY;
if(mBoxX > APP_WIDTH - 50) mBoxDX = -1; if(mBoxX < 0) mBoxDX = 1; if(mBoxY > APP_HEIGHT - 50) mBoxDY = -1; if(mBoxY < 0) mBoxDY = 1;
mGraphics = (Graphics2D)mBufferStrategy.getDrawGraphics(); mGraphics.clearRect(0, 0, APP_WIDTH, APP_HEIGHT); mGraphics.setColor(Color.RED); mGraphics.fillRect(mBoxX, mBoxY, 50, 50);
mGraphics.dispose(); mBufferStrategy.show();
mEnd = System.nanoTime(); mDT = mEnd - mStart;
while(mDT < mSetFPS) { Thread.yield(); mEnd = System.nanoTime(); mDT = mEnd - mStart; } } }
public static void main(String[] args) { new CTest(); } } |
Did I miss something on implementing a good active rendering game loop?