Skip to content

Instantly share code, notes, and snippets.

Created October 8, 2015 08:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/ab50c60a57eca465242e to your computer and use it in GitHub Desktop.
Save anonymous/ab50c60a57eca465242e to your computer and use it in GitHub Desktop.
public class SpaceGame implements Runnable{
public static final int WIDTH = 800;
public static final int HEIGHT = 600;
public static final int FPS_TARGET = 60;
public boolean running;
public void init() {
try {
Display.setDisplayMode(new DisplayMode(WIDTH, HEIGHT));
Display.setTitle("Space Game");
Display.setVSyncEnabled(true);
Display.setResizable(false);
Display.create(new PixelFormat(), new ContextAttribs(3, 2)
.withForwardCompatible(true).withProfileCore(true));
} catch (LWJGLException e) {
e.printStackTrace();
}
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glViewport(0, 0, WIDTH, HEIGHT);
Mouse.setGrabbed(true);
}
public void tick() {
}
public void render() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBegin(GL_QUADS);
glColor4f(0.5f, 0.5f, 0.5f, 1);
glVertex3f(-50, 0, -50);
glVertex3f(-50, 0, 50);
glVertex3f(50, 0, 50);
glVertex3f(50, 0, -50);
glEnd();
}
@Override
public void run() {
long lastTime = System.nanoTime();
double unprocessed = 0;
double nsPerTick = 1000000000.0 / FPS_TARGET;
int frames = 0;
int ticks = 0;
long lastTimer1 = System.currentTimeMillis();
init();
while (running && !Display.isCloseRequested()
&& !Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) {
long now = System.nanoTime();
unprocessed += (now - lastTime) / nsPerTick;
lastTime = now;
boolean shouldRender = true;
while (unprocessed >= 1) {
ticks++;
tick();
unprocessed -= 1;
shouldRender = true;
}
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (shouldRender) {
frames++;
render();
//Display.sync(60);
Display.update();
}
if (System.currentTimeMillis() - lastTimer1 > 1000) {
lastTimer1 += 1000;
System.out.println(ticks + " ticks, " + frames + " fps");
frames = 0;
ticks = 0;
}
}
stop();
}
public static void main(String[] agrs) {
new SpaceGame().start();
}
public void start() {
running = true;
}
public void stop(){
Display.destroy();
running = false;
System.exit(1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment