Kotlin/Wasm 和键盘事件

问题描述 投票:0回答:1

嗨,我一直在尝试查找有关此内容的任何文档,但找不到任何内容,我尝试使用桌面撰写方法,但没有运气,我无法用键盘箭头移动单个方块,如果有人可以给我关于如何在 kotlin/wasm 中存档它的指示我很感激。


@Composable
@Preview
fun mainScreen() {
    var xPosition by remember { mutableStateOf(50f) }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(color = Color.Red)
            .onPreviewKeyEvent { event: KeyEvent ->
                if (event.type == KeyEventType.KeyDown) {
                    when (event.key) {
                        Key.DirectionLeft -> { // Left arrow key
                            xPosition -= 10f
                            true
                        }
                        Key.DirectionRight -> { // Right arrow key
                            xPosition += 10f
                            true
                        }
                        else -> false
                    }
                } else false
            },
        verticalArrangement = Arrangement.Center
    ) {
        Box(
            modifier = Modifier
                .size(100.dp)
        ) {
            Canvas(modifier = Modifier.fillMaxSize()) {
                drawRect(
                    color = Color.Blue,
                    topLeft = androidx.compose.ui.geometry.Offset(xPosition, 0f),
                    size = androidx.compose.ui.geometry.Size(100f, 100f)
                )
            }
        }
    }
}
kotlin android-jetpack-compose webassembly
1个回答
0
投票

经过一系列测试,我能够弄清楚一些事情,希望它对其他人有帮助:)

@Composable
fun mainScreen() {
    val squareX = remember { mutableStateOf(50.dp) }
    val squareY = remember { mutableStateOf(50.dp) }
    val squareSize = 100.dp

    keyboardEventHandler(squareX, squareY)
    movableBox(squareX.value, squareY.value, squareSize)
}

@Composable
fun movableBox(x: Dp, y: Dp, size: Dp) {
    Box(
        modifier = Modifier
            .size(size)
            .offset(x = x, y = y)
            .background(Color.Green)
    )
}

@Composable
fun keyboardEventHandler(squareX: MutableState<Dp>, squareY: MutableState<Dp>) {
    LaunchedEffect(key1 = true) {
        val handleKeyDown: (Event) -> Unit = { event ->
            (event as KeyboardEvent).let {
                when (it.key) {
                    "ArrowLeft" -> squareX.value -= 5.dp
                    "ArrowRight" -> squareX.value += 5.dp
                    "ArrowUp" -> squareY.value -= 5.dp
                    "ArrowDown" -> squareY.value += 5.dp
                }
            }
        }

        window.addEventListener("keydown", handleKeyDown)

        window.removeEventListener("keydown", handleKeyDown)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.