Alyona
Alyona

Reputation: 65

How to detect 2 drag gestures independently in Jetpack Compose?

I want to create a game for 2 people, where each person has to control a plane by dragging his finger. But I don't see any methods in Compose to detect the second drag.

The onDragStart method is not called for the second drag when I press the screen with two fingers.

My code:

@Composable
fun AirRacesContent() {

    var boxWidth by remember { mutableStateOf(0.dp) }
    var boxHeight by remember { mutableStateOf(0.dp) }

    val density = LocalDensity.current

    val TAG = "AirRacesContent"

    Box(modifier = Modifier
        .fillMaxSize()
        .paint(painterResource(id = R.drawable.background), contentScale = ContentScale.FillBounds)
        .onSizeChanged { size ->
            with(density) {
                boxWidth = size.width.toDp()
                boxHeight = size.height.toDp()
            }
        }
        .pointerInput(Unit){
            detectDragGestures (
                onDragStart = {offset -> 
                    Log.d(TAG, "drag start: $offset")
                },
                onDrag = { change, dragAmount ->
                    
                }
            )
        }) {
        val planeSize = 70.dp
        Image(
            painter = painterResource(id = R.drawable.plane1),
            contentDescription = null,
            modifier = Modifier.size(planeSize)
                .offset(boxWidth / 4 - planeSize/2, boxHeight * 8 / 10)
        )

        Image(
            painter = painterResource(id = R.drawable.plane2),
            contentDescription = null,
            modifier = Modifier.size(planeSize)
                .offset(boxWidth / 4 * 3 - planeSize/2, boxHeight * 8 / 10)
        )
    }
}

Upvotes: 0

Views: 142

Answers (1)

Alyona
Alyona

Reputation: 65

I figured out how to do this. I have created two Boxes inside main Box (for the 1st half of the screen and for the 2nd half) and use detectDragGestures for them separately.

Box(
    modifier = Modifier
        .fillMaxHeight()
        .width(screenWidth / 2)
        .pointerInput(Unit) {
            detectDragGestures(
                onDragStart = { offset ->
                    Log.d(TAG, "drag start: $offset")
                },
                onDrag = { change, dragAmount ->
        
                }
            )
        }
    )
Box(
    modifier = Modifier
        .fillMaxHeight()
        .width(screenWidth / 2)
        .offset(screenWidth / 2)
        .pointerInput(Unit) {
            detectDragGestures(
                onDragStart = { offset ->
                    Log.d(TAG, "drag start: $offset")
                },
                onDrag = { change, dragAmount ->
        
                }
            )
        }
)

Upvotes: 0

Related Questions