/** The main loop, that controls all the action. It repeats until game over. */ public void run() { long start = System.nanoTime(); long elapsed; long wait; final int minTimeBetweenFrames = 5; while (running) { // Timing // elapsed is the number of nanoseconds since last frame elapsed = System.nanoTime() - start; elapsed = Math.min(MAX_FRAME, elapsed); start = System.nanoTime(); Point pos = hero.getPos(); frame++; // Physics! simulate(hero, elapsed); // Move camera updateCamPos(); // Test 'victory' conditions if (pos.y < LOWER_BOUND) { running = false; } // Test world events (like touching a light) testTriggers(triggers); // Delete (release) dead effects. deleteDeadEntities(); // redraw everything repaint(); // "elapsed" is reassigned to the number of nanoseconds // since this frame began elapsed = System.nanoTime() - start; // wait is how much time is remaining // before the next frame needs to be drawn. wait = targetTime - elapsed / NS_PER_MS; // wait at least 5 ms between frames. if (wait < 0) { wait = minTimeBetweenFrames; } try { Thread.sleep(wait); } catch (InterruptedException e) { e.printStackTrace(); } } // end while } // end run
/** Move the camera so that our hero doesn't go off-screen. */ private void updateCamPos() { final int marginX = (int) (getWidth() * 0.25); final int marginTop = (int) (getHeight() * 0.2); final int marginBottom = (int) (getHeight() * 0.2); Point pos = hero.getPos(); Dimension dim = hero.getSize(); // update x motion // If too far left if (pos.x - marginX < offX) { offX = pos.x - marginX; // if too far right } else if (pos.x + marginX > offX + getWidth() - dim.width) { offX = pos.x + marginX - getWidth() + dim.width; } // update y motion // If too low if (pos.y - marginBottom < offY) { offY = pos.y - marginBottom; // If too high } else if (pos.y + marginTop > offY + getHeight() - dim.height) { offY = pos.y + marginTop - getHeight() + dim.height; } }