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

时间:2011-01-15 23:27:29

标签: c# math geometry

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

Point a = agent.Location;
Point b = agentToMoveToward.Location;

//---    important        
double diff = (b.X - a.X) + (b.Y - a.Y);
double euclideanNorm = Math.Sqrt(Math.Pow((b.X - a.X), 2) + Math.Pow((b.Y - a.Y), 2));
double offset = _config.StepSize * ( diff / euclideanNorm );

agent.NextLocation = new Point(a.X + offset, a.Y + offset);
//---

这是对的吗?

1 个答案:

答案 0 :(得分:10)

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

正确的公式是:

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

在C#中,只使用一个简单的Point类和Math库,如下所示:

public Point MovePointTowards(Point a, Point b, double distance)
{
    var vector = new Point(b.X - a.X, b.Y - a.Y);
    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(a.X + unitVector.X * distance, a.Y + unitVector.Y * distance);
}

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