Answer the question
In order to leave comments, you need to log in
How to remove lags when moving an imageView?
I am writing an Android app in Kotlin.
The essence of the application: imageview moves from top to bottom and ricochets from bottom to top (x coordinate is static). This imageview is like an endless jumper. **BUT:**
When you click on the imageview (which itself moves from the top wall to the bottom and vice versa), the movement speed should increase (the higher the movement speed, the harder it is to hit. This is the point of the game).
I implemented through such "physics":
// btnBall - imageview, по нажатию которой увеличивается скорость передвижения
val btnBall = findViewById<ImageButton>(R.id.btnBall)
var speed_of_ball = 500F
btnBall.setOnClickListener(object : View.OnClickListener {
override fun onClick(view: View?) {
speed_of_ball += 10
}
})
// кнопка старт игры
ButtonStartGame.setOnClickListener {
val display = windowManager.defaultDisplay
val size = Point()
display.getSize(size)
val height: Int = size.y
var dt = 0.01
var yVel = speed_of_ball
var y = 1.0
var yPos = 0F
var flag_go_up = false
btnBall.y = yPos
GlobalScope.launch(context = Dispatchers.Main) {
while (true) { // бесконечный цикл передвижения в корутине
if (!flag_go_up) {
yPos += (dt * yVel).toFloat()
yVel += (dt * y).toFloat()
y += 0.01
btnBall.y = yPos
delay(5)
// проверка, что imageview не вышла за нижние границы экрана
if (yPos >= (height - btnBall.height)) {
flag_go_up = true
y = 1.0
yVel = speed_of_ball
}
} else { // иначе imageview перемещается снизу вверх
yPos -= (dt * yVel).toFloat()
yVel += (dt * y).toFloat()
y += 0.01
btnBall.y = yPos
delay(5)
if (yPos <= 0) {
flag_go_up = false
y = 1.0
yVel = speed_of_ball
}
}
}
}
}
Answer the question
In order to leave comments, you need to log in
You don't have to do that. No endless loops.
Have a look at the animators api , and don't animate by changing coordinates. There is translationX/translationY for this.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question