Algorithm to detect long and normal keyPressed event in java -
i'm developing little 2d game mario bros, in game when user press jump button depends of milliseconds jump button pressed, mario performs little jump or larger jump. tried declare counter increments keypressed event 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 sec pj[0].setvelocidady(-15); } if(contadortiemposalto > 0){ pj[0].setvelocidady(-25); } contadorsalto++; } }
i can paste rest of code if want! thanks
instead of recording key has been pressed in map, record when key has been pressed. add together keyreleased() handler clears key map.
you can find out how long 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 pressed , how long long t = keypressmap.get(keyevent.vk_space); if (t == null) { // not pressed } else { // pressed x milliseconds long millis = t - system.currenttimemillis(); }
you can decide on how long key has been down.
java events keypress 2d-games
No comments:
Post a Comment