当我的球碰到篮筐时如何加分?如何判断球与篮的触感?
Posted
技术标签:
【中文标题】当我的球碰到篮筐时如何加分?如何判断球与篮的触感?【英文标题】:How add point when my ball touch basket? how to determine the touch of the ball and basket? 【发布时间】:2021-07-28 20:30:25 【问题描述】:如何检测球和篮筐的接触并为得分加分?
我有一个球和一个篮筐。篮子在 x 轴上移动。 球 - 按下时的 y 轴
请帮帮我
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)
【问题讨论】:
【参考方案1】:您可以发布一个可运行的对象来检查所有内容的当前位置,然后在最后重新发布它自己,以便它在每个滴答声中运行
// 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()
我很懒,只是将其发布在视图(篮子)上,但如果您愿意,可以获取 Handler
。
更好的方法是使用animation listener、ValueAnimator.AnimatorUpdateListener
来执行此操作 - 该链接会告诉您如何操作。实现onAnimationUpdate
并在那里进行检查,而不是不断发布可运行文件 - 这样检查仅在动画运行时发生。这意味着使用value animator 至少为一件事(可能是球)设置动画,这需要更多的工作
【讨论】:
非常感谢!当您可以实现此功能时,我会通知您)再次感谢您)以上是关于当我的球碰到篮筐时如何加分?如何判断球与篮的触感?的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 Actionscript 3 为在 z 轴上弹跳的球设置动画?