[RESOLVED] [2005] Move Towards Mouse
How can I get a picturebox to move towards the mouse?
I've tried the following code but it doesn't work properly.
It doesn't go straight to the mouse(direction between points?) it either goes up/down or left/right until it reaches the mouse:
I have 2 variables; 'mouseLeft' and 'mouseTop' that get the mouse position in the 'Main_MouseMove' event.
Code:
If mouseLeft > picMove.Left Then
picMove.Left += 3
End If
If mouseLeft < picMove.Left Then
picMove.Left -= 3
End If
If mouseTop > picMove.Top Then
picMove.Top += 3
End If
If mouseTop < picMove.Top Then
picMove.Top -= 3
End If
Thanks in advance, knxrb :D
Re: [2005]Move Towards Mouse
Re: [2005] Move Towards Mouse
are you looking for animation here?
Re: [2005] Move Towards Mouse
Try this:
Put a timer control and a picturebox on the form and this code:
You can alter the MoveUnits and the Timer1.Interval to get the desired speed and tolerence.
vb.net Code:
Public Class Form1
Const MoveUnits As Integer = 5
Dim mouseX, mouseY As Integer
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Timer1.Interval = 5
Timer1.Enabled = True
End Sub
Private Sub Form1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseMove
mouseX = e.X
mouseY = e.Y
End Sub
Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim nX, nY As Integer
nX = PictureBox1.Left + PictureBox1.Width \ 2
nY = PictureBox1.Top + PictureBox1.Height \ 2
If mouseX > nX Then nX += MoveUnits Else nX -= MoveUnits
If mouseY > nY Then nY += MoveUnits Else nY -= MoveUnits
If Math.Abs(mouseX - nX) > MoveUnits Then PictureBox1.Left = nX - PictureBox1.Width \ 2
If Math.Abs(mouseY - nY) > MoveUnits Then PictureBox1.Top = nY - PictureBox1.Height \ 2
End Sub
End Class
Pradeep :)
Re: [2005] Move Towards Mouse
[EDIT] How would I get the form to paint a line to where it is going next?
Example: the picturebox is going left so the form will draw a line to where the picturebox will change direction left until it changes direction. (See pic below for better example)
http://www.rkwebcreations.co.uk/picline.png
[EDIT]
kleinma: Not really animation, I just want to have a control move towards my mouse. I think Pradeep has solved it now, thanks anyway :)
Pradeep1210: Thanks, it works better than mine :)
Re: [2005] Move Towards Mouse
I can't understand what you are trying to achieve.
Is the point of meeting of blue and red lines the current mouse position?
Should those lines always be perpendicular to each other?
what is the circle (and the rectangle which I assume is the picturebox) in that drawing?
Re: [2005] Move Towards Mouse
It's alright I've sorted it now:
Code:
e.Graphics.DrawLine(Pens.Green, picPixel.Left, picPixel.Top, picPixel.Left, picMove.Top)
e.Graphics.DrawLine(Pens.Green, picMove.Left, picMove.Top, picPixel.Left, picMove.Top)
http://www.rkwebcreations.co.uk/linepic.png