how can I detect the touch of the ball and basket and add a point to the score?
I have a ball and basket. the basket moves on the x-axis. Ball - y-axis when pressed
Please, help me
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val basket: ImageView = findViewById(R.id.imageViewBasket)
val basketball: ImageView = findViewById(R.id.imageViewBasketball)
val textViewScore: TextView = findViewById(R.id.textViewScore)
var score = 0
val wm: WindowManager = windowManager
val disp: Display = wm.defaultDisplay
val size = Point()
disp.getSize(size)
val screenWidth = size.x
val screenHeight = size.y
var ballY = basketball.y
var ballX = basketball.x
val basketX = basket.x
val basketY = basket.y
var ballCenterX = ballX + basketball.width /2f
val ballCenterY = ballY + basketball.height /2
val animationFromLeftToRight = TranslateAnimation(0f, 750f, 0f, 0f)
animationFromLeftToRight.apply {
duration = 2000
repeatMode = Animation.RELATIVE_TO_PARENT
repeatCount = -1
}
basket.startAnimation(animationFromLeftToRight)
basketball.setOnClickListener {
val ballUp = TranslateAnimation(0f, 0f, 0f, -1500f)
ballUp.apply {
duration = 700
repeatMode = Animation.RESTART
}
basketball.startAnimation(ballUp)
}
}
You could post a runnable that checks the current position of everything, and then reposts itself at the end so it runs every tick
I'm being lazy and just posting it on a view (the basket) but you could grab a
Handlerif you want.A better way would be to do this with an animation listener,
ValueAnimator.AnimatorUpdateListenerspecifically - the link tells you how to do it. ImplementonAnimationUpdateand do the check in there, instead of constantly posting a runnable - this way the check is only happening while the anim is running. It would mean animating at least one thing (probably the ball) using a value animator though, which is a little more work