Created
January 5, 2022 04:17
-
-
Save eddieberklee/99cd55c7fc10464688b3fbb477f42e8f to your computer and use it in GitHub Desktop.
Using sensor to translation animate view
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| val sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager | |
| sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)?.let { accelerometer -> | |
| sensorManager.registerListener(object : SensorEventListener { | |
| override fun onSensorChanged(event: SensorEvent) { | |
| val x = event.values[0] | |
| val y = event.values[1] | |
| val z = event.values[2] | |
| Timber.d("x: $x y: $y z: $z") | |
| val xAnimation = SpringAnimation(binding.root, DynamicAnimation.TRANSLATION_X).apply { | |
| spring = SpringForce().apply { | |
| dampingRatio = 0.4f | |
| stiffness = 300f | |
| } | |
| } | |
| val yAnimation = SpringAnimation(binding.root, DynamicAnimation.TRANSLATION_Y).apply { | |
| spring = SpringForce().apply { | |
| dampingRatio = 0.4f | |
| stiffness = 300f | |
| } | |
| } | |
| xAnimation.animateToFinalPosition( | |
| Etil.mapValueClamped( | |
| x, | |
| -40f, | |
| 40f, | |
| 300f.dpToPx, | |
| -300f.dpToPx | |
| ) | |
| ) | |
| yAnimation.animateToFinalPosition( | |
| Etil.mapValueClamped( | |
| y, | |
| -40f, | |
| 40f, | |
| -150f.dpToPx, | |
| 150f.dpToPx | |
| ) | |
| ) | |
| } | |
| override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) = Unit | |
| }, accelerometer, SensorManager.SENSOR_DELAY_UI) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment