简体   繁体   中英

Moving images with the arrow keys in Java

I am writing a small game in java and an obvious key component is being able to move the character with the arrow keys. However I cannot get all directions to work, and only the last two if statements of the following block actually activate.

public void Update(){
    if(Canvas.keyboardKeyState(KeyEvent.VK_UP))
        yVel = -1;
    else
        yVel = 0;

    if(Canvas.keyboardKeyState(KeyEvent.VK_LEFT))
        xVel = -1;
    else
        xVel = 0;

    if(Canvas.keyboardKeyState(KeyEvent.VK_DOWN))
        yVel = 1;
    else
        yVel = 0;

    if(Canvas.keyboardKeyState(KeyEvent.VK_RIGHT))
        xVel = 1;
    else
        xVel = 0;

    x += xVel;
    y += yVel;
}

My inputs are good, all keys are registering, but no math is taking place. If anyone has suggestions or a library/package that would make this easier, please let me know.

You override the values in the else blocks. You maybe want to do this.

public void Update(){

    xVel = 0;
    yVel = 0;

    if(Canvas.keyboardKeyState(KeyEvent.VK_UP)) {
        yVel -= 1;
    }

    if(Canvas.keyboardKeyState(KeyEvent.VK_LEFT)) {
        xVel -= 1;
    }

    if(Canvas.keyboardKeyState(KeyEvent.VK_DOWN)) {
        yVel += 1;
    }

    if(Canvas.keyboardKeyState(KeyEvent.VK_RIGHT)) {
        xVel += 1;
    }

    x += xVel;
    y += yVel;
}

Its very obvious. Everytime your loop gets executed it happens something like this:

If it executes the first if statement, it also executes the rest of the else statements .

it should be something like this:

xVal = 0;
yVal = 0;
if(keyDown){
    yVal++;
}
else if(keyUp){
    yVal--;
}
else if(keyLeft){
    xVal--;
}
else{
    xVal++;
}
//Your rest of the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM