Browse Source

Use local density instead of setting `fillMaxHeight` to 0.5f (#590)

pull/592/head
Sebastian Aigner 4 years ago committed by GitHub
parent
commit
aa017ea235
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 14
      examples/falling_balls/src/main/kotlin/Game.kt
  2. 2
      examples/falling_balls/src/main/kotlin/Piece.kt

14
examples/falling_balls/src/main/kotlin/Game.kt

@ -8,9 +8,8 @@ import androidx.compose.runtime.*
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.unit.IntSize import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.*
import androidx.compose.ui.unit.sp
import kotlin.random.Random import kotlin.random.Random
class Game { class Game {
@ -21,7 +20,7 @@ class Game {
) )
private var startTime = 0L private var startTime = 0L
var size by mutableStateOf(IntSize(0, 0)) var size by mutableStateOf(Pair(0.dp, 0.dp))
var pieces = mutableStateListOf<PieceData>() var pieces = mutableStateListOf<PieceData>()
private set private set
@ -75,6 +74,7 @@ class Game {
@Composable @Composable
fun FallingBallsGame() { fun FallingBallsGame() {
val game = remember { Game() } val game = remember { Game() }
val density = LocalDensity.current
Column { Column {
Text( Text(
"Catch balls!${if (game.finished) " Game over!" else ""}", "Catch balls!${if (game.finished) " Game over!" else ""}",
@ -110,9 +110,11 @@ fun FallingBallsGame() {
if (game.started) { if (game.started) {
Box(modifier = Modifier Box(modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.fillMaxHeight(0.5f) .fillMaxHeight()
.onSizeChanged { .onSizeChanged {
game.size = it with(density) {
game.size = it.width.toDp() to it.height.toDp()
}
} }
) { ) {
game.pieces.forEachIndexed { index, piece -> Piece(index, piece) } game.pieces.forEachIndexed { index, piece -> Piece(index, piece) }

2
examples/falling_balls/src/main/kotlin/Piece.kt

@ -41,7 +41,7 @@ data class PieceData(val game: Game, val velocity: Float, val color: Color) {
fun update(dt: Long) { fun update(dt: Long) {
if (clicked) return if (clicked) return
val delta = (dt / 1E8 * velocity).toFloat() val delta = (dt / 1E8 * velocity).toFloat()
position = if (position < game.size.height) position + delta else 0f position = if (position < game.size.second.value) position + delta else 0f
} }
fun click() { fun click() {

Loading…
Cancel
Save