I use key bindings to listen for keys, the program just listens for the left and right arrows to move the image (I create Space Invaders). However, there is a slight delay in the answer that I would like to get rid of. I read about it, but I see only a lot of vague answers. Many people seem to say to set a boolean when a key is pressed or released and listen to it in the game loop and act on the boolean. I tried this but get the same results. Any suggestions or examples on how to fix this problem?
Here is my code
public class Board extends JPanel implements ActionListener{ Timer timer; Tank tank; MoveRight moveRight; MoveLeft moveLeft; releaseMoveRight releasemoveRight; releaseMoveLeft releasemoveLeft; int tankdx = 0; boolean rightKeyDown; boolean leftKeyDown; boolean boardset; public Board(){ setBackground(Color.BLACK); ImageIcon alien1ii = new ImageIcon( this.getClass().getResource("si_Alien1.png")); Image alien1 = alien1ii.getImage(); ImageIcon alien2ii = new ImageIcon( this.getClass().getResource("si_Alien2.png")); Image alien2 = alien2ii.getImage(); ImageIcon alien3ii = new ImageIcon( this.getClass().getResource("si_Alien3.png")); Image alien3 = alien3ii.getImage(); timer = new Timer(5, this); timer.start(); tank = new Tank(); moveRight = new MoveRight(); moveLeft = new MoveLeft(); releasemoveRight = new releaseMoveRight(); releasemoveLeft = new releaseMoveLeft();
Here is a class of tanks
public class Tank { int x = 180; int y = 320; int dx; int tankSpeed; ImageIcon tankii = new ImageIcon(this.getClass().getResource("si_Tank.png")); Image tank = tankii.getImage(); public Image getTank(){ return tank; } public int getx(){ return x; } public int getY(){ return y; } public void move(int dx){ x += dx; } }
Another thing I should mention, I'm sure the delay is that I read the OS, I'm not sure. No delay occurs when you press one key. Or, if you hold your right hand, and then press left, it will move left without delay. It seems that the delay only occurs when you hold one direction and release it, and press the other direction at about the same time as this delay.
If anyone has any suggestions, this will be appreciated. thanks
source share