我有一个图像按钮,按下时我希望它指向用户的手指(等等,就像视频游戏中角色看着用户鼠标的方式)。但是它不起作用,并且无法正确跟踪手指。我认为这与我的逻辑有关,但我不确定。
这是我的代码:
findViewById<ImageButton>(R.id.leftButton).setOnTouchListener { _, motionEvent ->
//Will happen when image is pressed other wise event is set to false
when (motionEvent.action){
//change opacity of nob direction image when user holds finger on image
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE -> {
//remove directional image (not the image moving)
findViewById<ImageView>(R.id.leftButtonDerection).alpha = 0.0f
//get y and x value of finger
val x: Float = motionEvent.x
val y: Float = motionEvent.y
//find x and y value for nob image (this is where I think the problem is)
val nobCenterX = (findViewById<ImageButton>(R.id.leftButton).x + findViewById<ImageButton>(R.id.leftButton).width) / 2
val nobCenterY = (findViewById<ImageButton>(R.id.leftButton).y + findViewById<ImageButton>(R.id.leftButton).height) / 2
//calculate angle from finger to nob point
val angle = Math.toDegrees(atan2(y - nobCenterY, x - nobCenterX).toDouble())
//apply angle to nob image rotation
findViewById<ImageButton>(R.id.leftButton).rotation = angle.toFloat()
}
//when user lets go or the hold action is stopped
//it will reset the opacity of the direction image
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
findViewById<ImageView>(R.id.leftButtonDerection).alpha = 1.0f
findViewById<ImageButton>(R.id.leftButton).rotation = 0f
}
}
false
}
代码输出:
我想要的是图像能够进行完整的 360 旋转,这样一旦按下,它就可以跟随手指在任何位置。
感谢您的帮助。
第一个问题是你认为它在哪里,按钮中心与触摸坐标无关。
val nobCenterX = width / 2
val nobCenterY = height / 2
第二个问题是您正在旋转正在侦听触摸事件的同一视图,这将导致旋转抖动。我建议您在内部视图 (
leftButtonDerection
) 上监听触摸事件并旋转外部视图 (leftButton
)。