Xspeed = (mousePosition.X - object.Left) / 20;
Yspeed = (mousePosition.Y - object.Top) / 20;
x = x + Xspeed;
y = y + Yspeed;
object.location = new Point(x, y);
但它没有做我想做的事情。
首先,我强烈建议将点/向量用于此类事物,因为它使它变得更加容易,并消除了手工写出所有数学的需求。我正在使用system.numerics.vector2用于此示例,但是有很多矢量库可以正常工作,或者您可以编写自己的。
基本思想是将矢量分为方向和速度组件,并限制速度。
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;
注意,您可能必须在Winforms和您使用的任何矢量库之间编写一些转换代码。