我正在尝试制作一个简单的点击系统,当用户点击屏幕上的某个点时,一个对象(在这种情况下为椭圆形)将移动到该点。它有点工作,唯一的问题,如果它移动一点点鼠标的位置。我假设这与绘制椭圆的位置有关,我没有考虑到这一点:我有以下代码:
Public Class Form1
Dim formWidth, formHeight As Integer
Dim screenWidth As Integer = Screen.PrimaryScreen.Bounds.Width
Dim screenHeight As Integer = Screen.PrimaryScreen.Bounds.Height
Dim mousePos As Point
Dim ballPos As Point
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
formHeight = screenHeight - 200
formWidth = screenWidth - 300
Me.Size = New System.Drawing.Size(formWidth, formHeight)
Me.Location = New Point(5, 5)
ballTimer.Stop()
End Sub
Private Sub ballTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ballTimer.Tick
If ballPos.X < mousePos.X Then
ballPos.X += 20
ball.Location = ballPos
End If
If ballPos.X > mousePos.X Then
ballPos.X -= 20
ball.Location = ballPos
End If
If ballPos.Y < mousePos.Y Then
ballPos.Y += 20
ball.Location = ballPos
End If
If ballPos.Y > mousePos.Y Then
ballPos.Y -= 20
ball.Location = ballPos
End If
If ballPos = mousePos Then
ballTimer.Stop()
End If
End Sub
Private Sub Form1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseClick
ballPos = New Point(ball.Location.X, ball.Location.Y)
mousePos = New Point(MousePosition)
ballTimer.Start()
End Sub
End Class
我在让它完全移动到鼠标指针顶部时遇到了一些麻烦。有人可以帮我解决这个问题吗?感谢。
答案 0 :(得分:1)
唯一的问题是,它只是移动了一点鼠标
你以20步为单位移动球。当球在目标位置的20个像素范围内时,你应该将它移动到确切的位置,例如
If ballPos.X < mousePos.X Then
If mousePos.X - ballPos.X > 20 Then
ballPos.X += 20
Else
ballPos.X = mousePos.X
End If
ball.Location = ballPos
End If