LibGDX: Action when touchscreen is pressed and action when touchscreen is released

1.2k Views Asked by At

I have a problem with my code at libGDX in Android Studio. I'm trying to have an object perform an action while I press the screen. If I let go, the previous action should be aborted and a second should begin. When I press again on the screen, the second action should stop again and start the first while I hold down.

I have unfortunately no idea how I should do this and the Internet there is unfortunately also no exact information about it. This also means that I have no code, which I can show as an aid position.

I would be very happy if someone has a solution, or can help me. :)

4

There are 4 best solutions below

1
Tapan Kumar Patro On

You can use this way:

view.setOnTouchListener(new View.OnTouchListener() {        
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch(event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // PRESSED
                return true; // if you want to handle the touch event
            case MotionEvent.ACTION_UP:
                // RELEASED
                return true; // if you want to handle the touch event
        }
        return false;
    }
});

Let me know if this helps..

2
dfour On

I would use an input listener which has a boolean value called touching. Then in the touchDown event set the touching to true. Again in the input listener in the touchUp event set the touching to false.

public class MyController  implements InputProcessor {
    @Override
    public boolean touchUp(int screenX, int screenY, int pointer, int button) {
         touching = false;
    }

    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
         touching = true;
    }
    //.. more methods etc

}

In your application create this MyController and set it as the inputListsner with:

controller = new MyController();
Gdx.input.setInputProcessor(controller);

Now you can detect when the user is touching and do what ever action you need with:

if(controller.touching){
    //user is touching do touching action
}else{
    // user isn't touching do the non touchin action
}
0
AAryan On

You can use in this way inside render method :

if(Gdx.input.isTouched()){

    //whether the screen is currently touched.
}else{

}

or

  1. You can pass InputProcessor implemented class inside Gdx.input.setInputProcessor(..)

  2. after then override touchDown(..) and touchUp(...) method of that interface,

  3. choose flag or some other technique for your requirement.
0
giuseppe On

Tapped:

if (Gdx.input.justTouched()) {
//do something; }

Untapped:

if (Gdx.input.getPressure()==0){
//do something-else; }