Hi guys, I'm pretty new to programming, but I really want to make a game. I know this is a really easy question, but it is late, and I don't want to spend the next couple of hours doing something wrong. I want to move an object around with the keyboard, is this the best way of doing it? And how do I implements double buffering to avoid flicker?
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 96 97 98 99 100 101 102 103 104 105 106 107 108 109
|
import java.awt.*; import java.awt.geom.*; import java.awt.event.*; import javax.swing.*;
public class AnimationTest extends BasicJFrame implements Runnable { private Ellipse2D.Double cirkel; private double xpos = 250; private double ypos = 250; private double rad = 25; private double xspeed; private double yspeed; private Thread animationThread;
public AnimationTest() { super("Testarea", 500, 500); getContentPane().setBackground(Color.WHITE); addKeyListener(listener); xspeed = 0; yspeed = 0; setVisible (true); animationThread = new Thread(this); animationThread.start(); }
public void run() { while(Thread.currentThread() == animationThread) { xpos = xpos + xspeed; ypos = ypos + yspeed; repaint(); try { Thread.sleep(10); } catch(InterruptedException u) { System.err.println(u.toString()); } } } KeyListener listener = new KeyListener() { public void keyPressed(KeyEvent e) { int code = e.getKeyCode(); switch(code) { case KeyEvent.VK_UP: yspeed = -3; break; case KeyEvent.VK_LEFT: xspeed = -3; break; case KeyEvent.VK_RIGHT: xspeed = +3; break; case KeyEvent.VK_DOWN: yspeed = +3; break; } }; public void keyTyped(KeyEvent e) {}; public void keyReleased(KeyEvent e) { int code = e.getKeyCode(); switch(code) { case KeyEvent.VK_UP: yspeed = 0; break; case KeyEvent.VK_LEFT: xspeed = 0; break; case KeyEvent.VK_RIGHT: xspeed = 0; break; case KeyEvent.VK_DOWN: yspeed = 0; break; } }; }; public void paint(Graphics g) { super.paint(g); Graphics2D g2 = (Graphics2D) g; g2.setColor(Color.RED); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); cirkel = new Ellipse2D.Double(xpos - rad, ypos - rad, 2*rad, 2*rad); g2.fill(cirkel); } }
|
