Ich fang grad bissl mit Java an, und wollte ein Spiel machen, in dem man mit den Pfeiltasten ein Rechteck bewegt. Leider wird immer nur eine Taste ausgewertet. Das Rechteck kann sich also nicht in x und y Richtung bewegen....
Danke im Vorraus
Danke im Vorraus
Java:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class MainCode extends Applet implements Runnable, KeyListener {
private static final long serialVersionUID = 1L;
public static int width = 500, height = 500;
public static float maxFrameRate = 60.0f;
Image backbuffer;
Graphics backb;
int x;
int y;
int speed = 4;
public void init() {
this.addKeyListener(this);
new Thread(this).start();
}
public void run() {
backbuffer = this.createImage(width, height);
backb = backbuffer.getGraphics();
backb.setColor(Color.white);
while (true) {
repaint();
try {
Thread.sleep((long) (1000.0f / maxFrameRate));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void paint(Graphics g) {
super.paint(g);
backb.setColor(Color.black);
backb.fillRect(0, 0, width, height);
backb.setColor(Color.red);
backb.fillRect(x, y, 10, 50);
g.drawImage(backbuffer, 0, 0, this);
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
int kc = e.getKeyCode();
if (e.getKeyCode() == KeyEvent.VK_LEFT)
x -= speed;
if (e.getKeyCode() == KeyEvent.VK_RIGHT)
x += speed;
if (e.getKeyCode() == KeyEvent.VK_UP)
y -= speed;
if (e.getKeyCode() == KeyEvent.VK_DOWN)
y += speed;
}
public void keyReleased(KeyEvent e) {
}
}