C # smooth objects movement

I have all the necessary code to move and click with the C # code, but I do not want to just set the mouse position in X and Y ; it will look jerky. Instead, I want to have a smooth transition from point X1, Y1 to point X2, Y2 in Z seconds. Like keyframing.

I am looking for a method similar to this:

 public void TransitionMouse(int x, int y, double durationInSecs) 

It just smoothly moves the mouse from its current position to X and Y in durationInSecs seconds. I have a function:

 public void MoveMouse(int x, int y) 

This instantly moves the mouse in X , Y


EDIT

Thanks for the help guys! Here is the finished and verified code:

  [DllImport("user32.dll")] static extern bool SetCursorPos(int X, int Y); public void TransitionMouseTo(double x, double y, double durationSecs) { double frames = durationSecs*100; PointF vector = new PointF(); PointF mousePos = Cursor.Position; vector.X = (float)((x - mousePos.X) / frames); vector.Y = (float)((y - mousePos.Y) / frames); for (int i = 0; i < frames; i++) { SetCursorPos((int)(mousePos.X += vector.X), (int)(mousePos.Y += vector.Y)); Thread.Sleep((int)((durationSecs / frames) * 1000.0)); } } 
+4
source share
2 answers

You can do this in several ways. One option would be to compute the vector needed to move the mouse in each frame and apply it over a period of time to the position of the mouse.

So, if we are in position 5.5 and want to move to 20.30 over 10 frames, our vector will be as follows:

val = (target - start) / frames;

x = (20 - 5) / 10; y = (30 - 5) / 10;

Vector = 1,5,2,5

Then, in your TransitionMouse method, you slowly snap the vector to the mouse position for any duration, using the Thread.Sleep method to control the speed. The code might look like this:

 public void TransitionMouseTo(int x, int y, int durationSecs) { int frames = 10; PointF vector = new PointF(); vector.X = (x - Cursor.Position.X) / frames; vector.Y = (y - Cursor.Position.Y) / frames; for (int i = 0; i < frames; i++) { Point pos = Cursor.Position; pos.X += vector.X; pos.Y += vector.Y; Cursor.Position = pos; Thread.Sleep((durationSecs / frames) * 1000); } } 

Another way to do this is to use the Bresenhams algorithm to calculate all the points that the mouse cursor will move, then scroll through each point and apply it to the cursor again using Thread.Sleep to save the correct time.

Steve

+7
source

really depends on your definition of smoothness, but most smooth motion algorithms use spline to interpolate between 2 or more data points.

this may help http://geekswithblogs.net/JuanDoNeblo/archive/2007/10/25/Data-Interpolation-with-SPLINE-in-Csharp.aspx

0
source

All Articles