The problem is, if I hold down one of the arrow keys there is a delay between moving constantly. What I mean is if I hold down left, it will move 7 pixels, then a little wit later it moves constantly. can someone tell me how to fix this so it moves “smoothly”
code——————–
package game;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
public class GamePlay implements KeyListener{
int shipX = 400;
int shipY = 300;
public int shipSpeed = 7;
public void incShipX(int i) {this.shipX += i;}
public void incShipY(int i) {this.shipY += i;}
Image ship;
File shipFile = new File("C:/Users/Pictures/ship.png");
public GamePlay() {
try {
ship = ImageIO.read(shipFile);
} catch (IOException ex) {
Logger.getLogger(GamePlay.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void drawShip(Graphics g) {
g.drawImage(ship, shipX, shipY, null);
}
@Override
public void keyTyped(KeyEvent ke) {
}
@Override
public void keyPressed(KeyEvent ke) {
if(ke.getKeyCode() == KeyEvent.VK_LEFT) {
incShipX(-shipSpeed);
}
if(ke.getKeyCode() == KeyEvent.VK_RIGHT) {
incShipX(shipSpeed);
}
if(ke.getKeyCode() == KeyEvent.VK_UP) {
incShipY(-shipSpeed);
}
if(ke.getKeyCode() == KeyEvent.VK_DOWN) {
incShipY(shipSpeed);
}
}
@Override
public void keyReleased(KeyEvent ke) {
}
}
I am adding the keyListener to my Canvas—add(gamePlay);
When you press your arrow key, your operating system only sends a single key pressed event to your Java application. This means pressing the key will only cause your ship to move once.
If you hold down your key, after a delay, your operating system will start sending repeated key pressed events. If I press and hold my ‘s’ key here… ssssssssssssssssssssss my first ‘s’ appeared immediately, then there was a short delay, and then the rest of the ‘s’ characters came in quickly. This is the same thing happening in your program.
To correct this, you need to update your ship at a regular interval (or at a variable interval if you account for the time delta when updating the ship). Note an important distinction: a key being pressed happens at an instant of time, whereas the state of the key is a function over time (values being UP or DOWN).
Not sure if I muddled the issue for you. I can try to explain differently if you require.