1
\$\begingroup\$

i stated coding my first game in java, i need some help in imlementing KeyListener to fit my game. after some search in tutorials i've imlemented it like this :

frame.addKeyListener(new KeyAdapter(){

private boolean[] keys = new boolean[120];
public boolean up , down , left , right;



public void tick() {
    up =  keys[KeyEvent.VK_UP] || keys[KeyEvent.VK_W];    
    down =  keys[KeyEvent.VK_DOWN] || keys[KeyEvent.VK_S];  
    left =  keys[KeyEvent.VK_LEFT] || keys[KeyEvent.VK_A];
    right =  keys[KeyEvent.VK_RIGHT] || keys[KeyEvent.VK_D];
}

public void keyPressed(KeyEvent e) {
    if(e.getKeyCode() != KeyEvent.VK_F5) keys[e.getKeyCode()] = true;
    tick();
    if (up){
        yMap+=4;
        direction='n';
        xInd=0;
    }
    else if(down){
        yMap-=4;
        direction='s';
        xInd=2;
    }
    else if(right){
        xMap-=4;
        direction='e';
        xInd=1;
    }
    else if(left){
        xMap+=4;
        direction='w';
        xInd=3;
    }
    wait++;
    if(wait==5){
        yInd++;
        wait=0;
    }
    if(yInd==3)
        yInd=0;
    cha=sprites[xInd][yInd];
    panel.repaint();
}

public void keyReleased(KeyEvent e) {
    keys[e.getKeyCode()] = false;
    tick();
    yInd=0;
    cha=sprites[xInd][yInd];
    panel.repaint();
}

public void keyTyped(KeyEvent e) {  
}
});

however every thing is fine in this code, the character is moving correctly the sprites are perfect but it is missing only one thing, the only thing i need is when i move the character in a direction, lets say for exemple UP, with a simple click on the up button (which normaly should make it move with only 4 pixels to up), the character should complete walking to the next square automaticaly (each square is 32*32 pixels). i hope i explained well my question and sorry for bad english !

\$\endgroup\$
1
\$\begingroup\$

Do not put your movement code in the key event handler. The event is fired once, when the key is pressed or released. If you want to continually move you need to put your actual movement code somewhere outside of the key event handler, presumably in your update method (or some idle function handler that is called every frame).

\$\endgroup\$
  • \$\begingroup\$ i hope you can add an exemple how should i do and thx a lot \$\endgroup\$ – Youssef Jan 11 '14 at 23:15
  • \$\begingroup\$ Youssef: I 'm not sure how the Java API exposes that functionality, but this indicates that the repaint method is a place to start (though it may not be the best solution): gamedev.stackexchange.com/questions/56956/… If that doesn't help, you should post a new question as follow-up to the linked one. \$\endgroup\$ – Sean Middleditch Jan 11 '14 at 23:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.