Reputation: 347
I am working on a game for a school project and as one step I have to bind keys to the image that will add/subtract from the x-y axis. However the way I have done it does not seem to work and instead of adding by a small amount increases the x/y by a lot and teleports the image away off of the screen.
The KeyListener code
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == 87) {
up = true ;
if (e.getKeyCode() == 65) {
left = true ;
}
if (e.getKeyCode() == 68) {
right = true ;
}
if (e.getKeyCode() == 83) {
down = true ;
}
}
}
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == 87) {
up = false ;
}
if (e.getKeyCode() == 65) {
left = false;
}
if (e.getKeyCode() == 68) {
right = false ;
}
if (e.getKeyCode() == 83) {
down = false ;
}
}
The Game Loop
public void run() {
while(running) {
//Player movement
if (up) {
y++ ;
}
if (left) {
x-- ;
}
if (right) {
x++;
}
if (down) {
y-- ;
}
//Player movement
}
}
Graphical Loop
protected void paintComponent(Graphics g) {
super.paintComponent(g);
//Graphical loop start
g.drawImage(Player, x, y, null) ;
//Graphical loop end
repaint();
Upvotes: 1
Views: 74
Reputation: 324108
Doesn't answer your question but:
if (e.getKeyCode() == 87)
Don't use "magic numbers". People don't know what "87" means. Use the field names provided by the API:
if (e.getKeyCode() == KeyEvent.VK_UP)
Also, in your paintComponent() method you have:
//Graphical loop end
repaint();
Don't ever invoke repaint() within a painting method. This will cause an infinite loop. Get rid of that code.
Upvotes: 3
Reputation:
The code works just the way it's supposed to. You only forgot one thing: the while
-loop for moving the image is running a lot faster than you seem to expect it to run. Simply insert a Thread.sleep(someDelay)
to make the loop run slower and the image should move with a more "userfriendly" speed.
Upvotes: 3