我想将二维搜索空间中的某个点 a 移动到具有一定步长(_config.StepSize = 0.03)的另一个点 b。
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);
//---
这是对的吗?
假设你的意思是你想移动一个点towards另一点,假设你的步长有距离单位,那么不,你的计算不正确。
正确的公式是:
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);
}
Edit:根据评论中的 TrevorSeniors 建议更新了代码
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)