Search code examples
javaandroidlibgdxtouch

How to detect number of fingers being used?


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


Solution

  • the easiest solution without using any listeners is to just iterate over some count of pointers and calling simple Gdx.input.isTouched() - you have to set some "maximum pointers count" but hey - peoples usually has only 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 reference:

    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 easily the position of touching pointer by using Gdx.input.getX() and Gdx.input.getY() like

        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)
            }
        }
    

    and then you can for example put it into array