Question

I know how to make the cursor move to a position using the following:

Cursor.Position = New Point(XPosition, YPosition)

But doing just that causes it to move there instantly, I would like for it to travel from the current position to the new position at a set speed.

The speed would be determined by two factors:

1 - The distance between the current and new position - EG. Going from 0X to 500X at a speed of 5px/s compared to going from 0X to 1000X at a speed of 10px/s).

2 - A limited timeframe to get to the target position.

I only know of a messy way of doing this which would be something similar to:

If Cursor.Position.X < XPosition Then 
    Dim Speed as Integer = XPosition - Cursor.Position.X
    While Cursor.Position.X < XPosition
        Cursor.Position = New Point(Cursor.Position.X + Speed, Blah..)
    End While
End If
'Etc..

This would require several If statements checking whether the current X/Y positions are over/under the target X/Y positions.

Is there any way I could make the code for doing this much cleaner?

Was it helpful?

Solution

It sounds like you need the parametric equation for a line:

x = x1 + (x2-x1)*t

where
x1 = start x,
x2 = end x, and
t = time between 0 and 1.

so if you wanted the cursor to move from x1(10,20) to x2(30,60) over 10 seconds...

1 second in:
x = 10 + (30-10)*.1 ; x = 12
y = 20 + (60-20)*.1 ; y = 24
2 seconds in:
x = 10 + (30-10)*.2 ; x = 14
y = 20 + (60-20)*.2 ; y = 28
3 seconds in:
x = 10 + (30-10)*.3 ; x = 16
y = 20 + (60-20)*.3 ; y = 32
etc.

Edit:
Ideone of this in action (don't use VB often, so its not perfect)
http://ideone.com/c9iLTA

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top