在c#中将点移动到另一个

我想将二维搜索空间中的某个点移动到具有一些步长的另一个点b(_config.StepSize = 0.03)。

Point a = agent.Location; Point b = agentToMoveToward.Location; //--- important double diff = (bX - aX) + (bY - aY); double euclideanNorm = Math.Sqrt(Math.Pow((bX - aX), 2) + Math.Pow((bY - aY), 2)); double offset = _config.StepSize * ( diff / euclideanNorm ); agent.NextLocation = new Point(aX + offset, aY + offset); //--- 

这是对的吗?

假设你的意思是你想将一个点移向另一个点并假设你的步长有距离单位,那么不,你的计算是不正确的。

正确的公式是:

  • nextLocation = a + UnitVector(a, b) * stepSize

在C#中,只使用一个简单的Point类和Math库,它看起来像:

 public Point MovePointTowards(Point a, Point b, double distance) { var vector = new Point(bX - aX, bY - aY); var length = Math.Sqrt(vector.X * vector.X + vector.Y * vector.Y); var unitVector = new Point(vector.X / length, vector.Y / length); return new Point(aX + unitVector.X * distance, aY + unitVector.Y * distance); } 

编辑:根据TrevorSeniors建议在评论中更新代码