How to move an object to the mouse with a set max speed in Windows Forms using C#

The problem is that I can't make the object follow my mouse at a certain speed. I managed to make it follow the mouse, but it increases the speed the further away it's and get slower the closer it's.

I tried doing this

Xspeed = (mousePosition.X - object.Left) / 20;
Yspeed = (mousePosition.Y - object.Top) / 20;

x = x + Xspeed;
y = y + Yspeed;

object.location = new Point(x, y);

But it doesn't do what I want it to do.

Upvotes: -1

Views: 50

Answers (1)

JonasH
JonasH

Reputation: 36566

First of, I would highly recommend using points/vectors for things like this, since it makes it much easier and removes the need to write out all the math by hand. I'm using System.Numerics.Vector2 for this example, but there are a bunch of vector libraries that would work fine, or you can write your own.

The basic idea is to separate the vector into a direction and speed component, and clamp the speed.

var objToMouse = mousePosition - object.location;

var speed = objToMouse.Length();
speed = Math.Min(speed, MaxSpeed); // clamp the speed
var deltaPos = Vector2.Normalize(objToMouse) * speed;

object.location += deltaPos;

Running this code in a timer should give you a maximal movement speed towards the mouse pointer. You might consider measuring the time between each timer tick using a stopwatch to make your speed independent of the timer interval, and to compensate for variations in the interval.

Note that you probably have to write some conversion code between winforms point and whatever vector library you are using.

Upvotes: 0

Related Questions