Elisey slode
Elisey slode

Reputation: 1

How add point when my ball touch basket? how to determine the touch of the ball and basket?

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)
        }

    }

Upvotes: -1

Views: 29

Answers (1)

cactustictacs
cactustictacs

Reputation: 19592

You could post a runnable that checks the current position of everything, and then reposts itself at the end so it runs every tick

// you'll probably have to calculate TOLERANCE based on screen density since it's pixels
fun Int.isCloseEnoughTo(other: Int) = abs(this - other) <= TOLERANCE

fun nothingButNet(): Boolean = 
    basketball.x.isCloseEnoughTo(basket.x) && basketball.y.isCloseEnoughTo(basket.y)

val basketCheck = object : Runnable {
    override fun run() {
        if (nothingButNet()) handleScore()
        basket.post(this)
    }
}

basketCheck.run()

I'm being lazy and just posting it on a view (the basket) but you could grab a Handler if you want.

A better way would be to do this with an animation listener, ValueAnimator.AnimatorUpdateListener specifically - the link tells you how to do it. Implement onAnimationUpdate and 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

Upvotes: 0

Related Questions