Search code examples
javalibgdx

Libgdx - About 2 player game. I want each player can touch his own area with one finger


I am creating 2 players game where each player has his own area. I want each player can touch his own area with one finger. So first I limit to "2 pointers" in the "touchdown" function.

public boolean touchDown(int screenX, int screenY, int pointer, int button){
    if(pointer > 1){
        return false;
    }
    Gdx.app.log("", "pointer: "+pointer);

    return false;
}

But the problem is if one player touch his own area with his 2 fingers another player won't be able to touch his own area. How can I resolve this problem ? Thank you.


Solution

  • You shouldn't reject based on the pointer number.

    If you want to allow the first pointer down on each side of the screen, you could do something like this (untested):

    private int player1Pointer = -1, player2Pointer = -1;
    private int player1X, player1Y, player2X, player2Y;
    
    //...
    
    public boolean touchDown(int screenX, int screenY, int pointer, int button){
    
        // Assuming top and bottom halves of screen:
        if (screenY > Gdx.graphics.getHeight() / 2){ // player 1 side
            if (player1Pointer >= 0) // player 1 already touching somewhere
                return false;
            player1Pointer = pointer;
            player1X = screenX;
            player1Y = screenY;
        } else { //player 2 side
            if (player2Pointer >= 0) // player 2 already touching somewhere
                return false;
            player2Pointer = pointer;
            player2X = screenX;
            player2Y = screenY;
        }
        return true;
    }
    
    public boolean touchDragged (int screenX, int screenY, int pointer) {
        if (pointer == player1Pointer){
            player1X = screenX;
            player1Y = screenY;
            return true;
        }
        if (pointer == player2Pointer){
            player2X = screenX;
            player2Y = screenY;
            return true;
        }
        return false;
    }
    
    public boolean touchUp (int screenX, int screenY, int pointer, int button) {
        if (pointer == player1Pointer){
            player1Pointer = -1;
            return true;
        }
        if (pointer == player2Pointer){
            player2Pointer = -1;
            return true;
        }
        return false;
    }