- #1
- 33
- 0
I have a program which uses a keyboard listener and moves a character in the program when the user places a key. However when the user lets go of the key the character keeps going a few more steps. I think what is happening is that I use a while loop and make it wait a few seconds in order to draw an animation for the character and while this is happening the keyboard is still taking in data and queuing it up then finishing everything in the queue after the player lets go of the button, I'm not completely sure if thats the problem, just what i think.
Here is the code im using:
the method gets called in the method keyPressed(KeyEvent e)
So I'm just wondering how to stop the character from moving right when the player lets go of the key instead of having the character continue to move for a few more steps. and the longer the player holds down a key the more steps the character takes after the player lets go.
Here is the code im using:
Code:
public void movePlayer(int deltaX, int deltaY) throws IOException
{
inMovement=true;
location[0]+=deltaX;
location[1]+=deltaY;
if(phaseNum==0)
{
phaseNum=1;
}
else if(phaseNum==1)
{
phaseNum=0;
}
playerPhase="player"+phaseNum+".gif";
File input = new File(playerPhase);
secondImage = ImageIO.read(input);
this.paintImmediately(0, 0, 500, 500);
long start=System.nanoTime();
//sets the variable start to the current time then waits 200000000 nanoseconds or 0.2 seconds
while(System.nanoTime()-start<105000000)
{
}
if(phaseNum==0)
{
phaseNum=1;
}
else if(phaseNum==1)
{
phaseNum=0;
}
playerPhase="player"+phaseNum+".gif";
input = new File(playerPhase);
secondImage = ImageIO.read(input);
location[0]+=deltaX;
location[1]+=deltaY;
this.paintImmediately(0, 0, 500, 500);
}
the method gets called in the method keyPressed(KeyEvent e)
So I'm just wondering how to stop the character from moving right when the player lets go of the key instead of having the character continue to move for a few more steps. and the longer the player holds down a key the more steps the character takes after the player lets go.