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

编程入门 行业动态 更新时间:2024-10-24 04:32:26
本文介绍了在c#中将点移动到另一个点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

Point a = agent.Location; Point b = agentToMoveToward.Location; // ---重要 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); // ---

它正确吗?

解决方案

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

正确的公式是:

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

简单的 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); 返回新的点(a.X + unitVector.X *距离,a.Y + unitVector.Y *距离);

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

I would like to move some point a in two dimensional search space to another point b with some stepsize (_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); //---

Is it correct?

解决方案

Assuming you mean you want to move one point towards another point and assuming your step size has distance units, then no, your calculation is not correct.

The correct formula is:

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

In C#, using just a simple Point class and the Math library, this looks like:

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: Updated code as per TrevorSeniors suggestion in comments

更多推荐

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

本文发布于:2023-11-09 10:19:53,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中将

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!