Java – How to detect the number of fingers in use?

How to detect the number of fingers in use?… here is a solution to the problem.

How to detect the number of fingers in use?

I’m making a game using Libgdx and I need to know if the user is using two fingers and if they are placed in the right place. One finger should be on the right side of the screen and the other finger on the left side of the screen.

Solution

The simplest solution, not using any listeners, is to just iterate over a few pointers and call simple Gdx.input.isTouched() – you have to set some “maximum pointer count”, but hey – people usually only have 20 fingers 🙂

    final int MAX_NUMBER_OF_POINTERS = 20;
    int pointers = 0;

for(int i = 0; i < MAX_NUMBER_OF_POINTERS; i++)
    {  
        if( Gdx.input.isTouched(i) ) pointers++;
    }

System.out.println( pointers );

Due to the quote:

Whether the screen is currently touched by the pointer with the given index. Pointers are indexed from 0 to n. The pointer id identifies the order in which the fingers went down on the screen, e.g. 0 is the first finger, 1 is the second and so on. When two fingers are touched down and the first one is lifted the second one keeps its index. If another finger is placed on the touch screen the first free index will be used.

You can also use Gdx.input.getX() and Gdx.input.getY() to easily locate the touch pointer

    final int MAX_NUMBER_OF_POINTERS = 20;
    int pointers = 0;

for(int i = 0; i < MAX_NUMBER_OF_POINTERS; i++)
    {  
        if( Gdx.input.isTouched(i) )
        {
            x = Gdx.input.getX(i);
            y = Gdx.input.getY(i)
        }
    }

Then you can put it into an array

Related Problems and Solutions