Search code examples
javaeventskeypress2d-games

Algorithm to detect long and normal keyPressed event in java


I'm developing a little 2D game like Mario Bros, in this game when the user press the jump button depends of the milliseconds the jump button is pressed, Mario performs a small jump or a larger jump. I tried to declare a counter that increments into my keyPressed event but not working...

contadorSalto = 0;
contadorTiempoSalto = 0;


public void keyPressed(KeyEvent arg0) {

        int codigo = arg0.getKeyCode();
        if(codigo == KeyEvent.VK_SPACE)
        {           
            System.out.println(contadorTiempoSalto);
            contadorTiempoSalto++; 
            map.put("espacio", true);
        }
}
public void moverPersonaje(){
if(map.get("espacio")&&(contadorSalto < 1)){
      if(contadorTiempoSalto == 0){//less tant 1 second
          pj[0].setVelocidadY(-15);
      }
      if(contadorTiempoSalto > 0){
          pj[0].setVelocidadY(-25);
      }
      contadorSalto++;
  }
}

I can paste the rest of code if you want! Thanks


Solution

  • Instead of just recording that a key has been pressed in your map, record when the key has been pressed. Also add a keyReleased() handler that clears the key from the map.

    You can then easily find out for how long the key has been pressed:

     public Map<Integer, Long> keyPressMap = new HashMap<>();
    
     public void keyPressed(KeyEvent arg0) {
        keyPressMap.put(arg0.getKeyCode(), System.currentTimeMillis());
     }
    
     public void keyReleased(KeyEvent arg0) {
        keyPressMap.remove(arg0.getKeyCode());
     }
    
     // find out if key is pressed and how long it was
     Long t = keyPressMap.get(KeyEvent.VK_SPACE);
     if (t == null) {
         // not pressed
     } else {
         // pressed for X milliseconds
         long millis = t - System.currentTimeMillis();
     }
    

    You can then decide what to do on how long the key has been down.