在坐标系中寻找相反的方向
给定的是笛卡尔坐标系和该系统内的点(x,y)。例如,点 p 的坐标为 (-12,2):
|
|
p |
|
------------------+------------------>
|
|
|
|
现在我需要一个函数/算法,根据坐标系中心 (0,0) 计算相反的“方向”(北、东、南、西)给定点。在我们的示例中,选择的最佳相反方向是东,沿着 X 轴向右。
然而,在我的应用程序中的某些情况下,并非所有方向都可以选择,在这种情况下,必须选择下一个最佳方向。在我们的示例中,如果 EAST 不可能,那么下一个最佳方向将是 SOUTH(然后是 NORTH,然后是 WEST)。
我可以用一些 if 语句来解决这个问题,但这似乎不太优雅。
还有其他(更好)的想法吗?
given is a Cartesian coordinate system and a point(x,y) within this system. For example a point p has the coordinates (-12,2):
|
|
p |
|
------------------+------------------>
|
|
|
|
Now I need a function/algorithm that calculates the opposite "direction" (north, east, south, west) from the coordinate system's center (0,0) based on the given point. In our example the best opposite direction to choose would be EAST, following the X-axis to the right.
However, in some situations within my application not all directions are an option to choose, in such a case the next-best direction has to be chosen. In our example, if EAST would not be possible, then the next-best direction would be SOUTH (then NORTH, then WEST).
I could solve this with some if-statements, but that does not seem to be very elegant.
Any other (better) ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用向量
(x, y)
与沿四个方向的单位向量的点积最小的数字对应于您想要的方向。然后是第二小的,依此类推。
这适用于任何方向,而不仅仅是 E、W、S 和 N - 您只需沿所需方向选取单位向量并比较点积
Use the dot product of your vector
(x, y)
with the unit vectors along the four directionsThe smallest number corresponds the direction you want. Then the second smallest, and so on.
This works for any directions not just E, W, S and N - you just need to pick unit vectors along the desired directions and compare the dot products
“真正”的相反方向是
-P
,即(12,-2)。“最佳”方向是较长的幅度,即(12,0)。将其归一化并得到 (1,0),即东边。
下一个最佳方向是较短的幅度,即(0,-2)。将其归一化后得到 (0,-1),即南方。
一般来说,如果您被限制沿着一组特定的单位向量,您可以使用具有最大点积的向量。
The 'true' opposite direction is
-P
i.e. (12,-2)The "best" direction is the longer magnitude, i.e. (12,0). You normalize it and get (1,0) which is east.
The next best direction is the shorter magnitude, i.e. (0,-2). You normalize it and get (0,-1) which is south.
In general, if you are constrained to go along a certain set of unit vectors, you use the one with the maximal dot product.