rross46
rross46

Reputation: 7

VB2010 Making an object move to the mouse pointer

I am trying to make a simple point and click system, whereby when the user clicks on a point on the screen, an object (in this case an oval) will move to that point. It kind of works, the only issue if that it moves just a little out of where the mouse is. I assume this is to do with the location where the oval is drawn from, I haven't taken that into account:I have the following code:

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

I am having a bit of trouble getting it to move exactly on top of the mouse pointer. Could someone help me with the mathematics on this one? Thanks.

Upvotes: 1

Views: 911

Answers (1)

Phillip Trelford
Phillip Trelford

Reputation: 6543

the only issue if that it moves just a little out of where the mouse is

You are moving the ball in steps of 20. When the ball is within 20 pixels of the target location you should move it to the exact location, e.g.

    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

Upvotes: 1

Related Questions