Peter Parker Peter Parker - 3 months ago 24
Android Question

Java LibGDX Multi Touch Issue

for (byte i = 0; i < 20; i++) {maxDistance = 10 * Gdx.graphics.getDeltaTime();
if (Gdx.input.isTouched(i) && Gdx.input.getY()<= 400) {
player1TouchPosition.set(Gdx.input.getX(i), Gdx.input.getY(i), 0);
camera.unproject(player1TouchPosition);
}
player1Tmp.set(player1TouchPosition.x, player1TouchPosition.y).sub(player1Rectangle.x, player1Rectangle.y);
if (player1Tmp.len() <= maxDistance) {
player1Rectangle.x = player1TouchPosition.x;
player1Rectangle.y = player1TouchPosition.y;
} else {
player1Tmp.nor().scl(maxDistance);
player1Rectangle.x += player1Tmp.x;
player1Rectangle.y += player1Tmp.y;
}
if (Gdx.input.isTouched(i) && Gdx.input.getY() >= 401) {
player2TouchPosition.set(Gdx.input.getX(i), Gdx.input.getY(i), 0);
camera.unproject(player2TouchPosition);
}
player2Tmp.set(player2TouchPosition.x, player2TouchPosition.y).sub(player2Rectangle.x, player2Rectangle.y);
if (player2Tmp.len() <= maxDistance) {
player2Rectangle.x = player2TouchPosition.x;
player2Rectangle.y = player2TouchPosition.y;
} else {
player2Tmp.nor().scl(maxDistance);
player2Rectangle.x += player2Tmp.x;
player2Rectangle.y += player2Tmp.y;
}
}


Hello I'm using this code to move to touch position. But I need multi touch. It's not working. When I add player2, it doesn't work. I didn't understand how is multi touch. How can I fix it?

Answer

Why do you not use InputProcessor? One example of one method from the interface

 @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        if(pointer =< 2){
            touches.get(pointer).touchX = screenX;
            touches.get(pointer).touchY = screenY;
            touches.get(pointer).touched = true;
        }
        return true;
    }

In the above example you can use maximum 2 touches. Actually 1 pointer is 1 touch.

Documentation

screenX and screenY are the touch position. Be aware you have to scale this position compared to your orthographic camera. A pointer is the pointer for the event.

If you create the InputProcessor you can launch it with

Gdx.input.setInputProcessor(/*Your class*/);

EDIT:

Example from the comments:

for (Button button : /*ArrayList*/{
            if (positionX >= button1.getX() && positionX <= button1.getX() + button1.getWidth() &&
                    positionY >= button1.getY() && positionY <= button1.getY() + button1.getHeight()){
        //Update the position
} 

You use this code inside the method from the interface touchDragged().