Skip to content

Instantly share code, notes, and snippets.

@pauloaapereira
Created April 23, 2021 23:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pauloaapereira/bb5bc77eaafafe56e4557ca44ab788cd to your computer and use it in GitHub Desktop.
Save pauloaapereira/bb5bc77eaafafe56e4557ca44ab788cd to your computer and use it in GitHub Desktop.
Jetpack Compose - Earthquake Effect_8
@Immutable
class EarthquakeMover : IEarthquakeMover {
override val x = Animatable(0.dp.value)
override val y = Animatable(0.dp.value)
override val rotation = Animatable(0.dp.value)
override val alpha = Animatable(1f)
override suspend fun move(shakeDuration: Int, shakeForce: Int) {
val shakeOffset = generateOffset(shakeForce)
val shakeRotation = generateRotation(shakeForce)
val shakeAlpha = generateAlpha()
x.animateTo(
targetValue = shakeOffset.x,
animationSpec = tween(shakeDuration)
)
y.animateTo(
targetValue = shakeOffset.y,
animationSpec = tween(shakeDuration)
)
rotation.animateTo(
targetValue = shakeRotation,
animationSpec = tween(shakeDuration)
)
alpha.animateTo(
targetValue = shakeAlpha,
animationSpec = tween(shakeDuration)
)
}
override suspend fun stop() {
x.animateTo(
targetValue = 0.dp.value,
animationSpec = tween(BackToNormalDuration)
)
y.animateTo(
targetValue = 0.dp.value,
animationSpec = tween(BackToNormalDuration)
)
rotation.animateTo(
targetValue = 0.dp.value,
animationSpec = tween(BackToNormalDuration)
)
alpha.animateTo(
targetValue = 1f,
animationSpec = tween(BackToNormalDuration)
)
x.stop()
y.stop()
rotation.stop()
alpha.stop()
}
override fun generateOffset(shakeForce: Int): Offset {
val x = Random.nextInt(-shakeForce, shakeForce)
val y = Random.nextInt(-shakeForce, shakeForce)
return Offset(x.toFloat(), y.toFloat())
}
override fun generateRotation(shakeForce: Int) =
Random.nextInt(-shakeForce, shakeForce).toFloat()
override fun generateAlpha() = Random.nextFloat().coerceAtLeast(.5f)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment