Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.Canvas;
- import java.awt.Color;
- import java.awt.Dimension;
- import java.awt.Graphics2D;
- import java.awt.image.BufferStrategy;
- import javax.swing.JFrame;
- import javax.swing.JPanel;
- /**
- * An example game canvas which renders using accelerated graphics and updates
- * with nanosecond precision.
- *
- * @author Ryan Greene
- *
- */
- @SuppressWarnings("serial")
- public final class GameCanvasTest extends Canvas {
- private static final long NANOSECONDS_PER_MILISECOND = 1000000;
- private static final long TICK_RATE = NANOSECONDS_PER_MILISECOND * 8;
- private final BufferStrategy strategy;
- public GameCanvasTest() {
- final JFrame container = new JFrame("Game");
- final JPanel panel = (JPanel) container.getContentPane();
- panel.setPreferredSize(new Dimension(800, 600));
- panel.setLayout(null);
- setBounds(0, 0, 800, 600);
- panel.add(this);
- setIgnoreRepaint(true);
- container.pack();
- container.setResizable(false);
- container.setVisible(true);
- container.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- requestFocus();
- createBufferStrategy(3);
- strategy = getBufferStrategy();
- }
- private double boxX = 0;
- private double boxY = 0;
- private double boxDX = .4;
- private double boxDY = .2;
- public void loop() {
- long lastTickTime = System.nanoTime();
- long delta;
- long sleepTime;
- Graphics2D g;
- while (true) {
- delta = System.nanoTime() - lastTickTime;
- lastTickTime = System.nanoTime();
- g = (Graphics2D) strategy.getDrawGraphics();
- // update
- boxX += (delta * boxDX) / NANOSECONDS_PER_MILISECOND;
- boxY += (delta * boxDY) / NANOSECONDS_PER_MILISECOND;
- // render
- g.setColor(Color.BLACK);
- g.fillRect(0, 0, 800, 600);
- g.setColor(Color.RED);
- g.drawRect((int) boxX, (int) boxY, 50, 50);
- g.dispose();
- strategy.show();
- sleepTime = TICK_RATE - (System.nanoTime() - lastTickTime);
- System.out.println("delta: " + delta + " sleep time: " + sleepTime + " (ms: " + sleepTime / NANOSECONDS_PER_MILISECOND + " ns: " + sleepTime % NANOSECONDS_PER_MILISECOND + ")");
- if (sleepTime > 0) {
- try {
- Thread.sleep(sleepTime / NANOSECONDS_PER_MILISECOND, (int) (sleepTime % NANOSECONDS_PER_MILISECOND));
- } catch (final InterruptedException e) {
- e.printStackTrace();
- }
- } else {
- System.out.println("[WARNING]: Load: " + (100 + Math.abs(sleepTime) / (TICK_RATE / 100)) + "%!");
- }
- }
- }
- public static void main(final String[] args) {
- new GameCanvasTest().loop();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement