Search code examples
javaandroidlibgdxdesktop-application

how to calculate time between button press and button release in libgdx


public void shotPower() {
    float startTime = System.currentTimeMillis();
        if (Gdx.input.getCurrentEventTime(Input.Keys.S)){
            float endTime = System.currentTimeMillis();

            float time = endTime - startTime;
            System.out.println(time);
    }
}

this code doesn't work.

I press button "S" and than press it for some time, I don't know how to calculate time between press and release. Maybe such method allready exists. I understand that it somehow connect with System.currentTimeMillis. Please help.

Sorry for my English, and I'm only begin to learn programming.


Solution

  • You're currently calculating the time it takes between the if statement, which will be very close to zero

    Use an InputProcessor instead. You will then have access to the methods keyDown() and keyUp() which you can use to compare the time. As both methods can't share local variables and we have multiple keys I'm using a HashMap to store the data.

    // integer is keycode, long is the time it was pressed
    private HashMap<Integer, Long> keyTime = new HashMap<Integer, Long>();
    
    @Override
    public boolean keyDown(int keyCode) {
    
        keyTime.put(keyCode, System.currentTimeMillis());
    
        return true;
    }
    
    @Override
    public boolean keyUp(int keyCode) {
    
        if(keyTime.containsKey(keyCode) {
            float time = endTime - keyTime.get(keyCode);
            System.out.println(time);
            keyTime.remove(keyCode);
        }
    
        return true;
    }