【发布时间】:2017-03-12 11:28:57
【问题描述】:
问题 我怎样才能找到一个矩形 w.r.t 到另一个矩形的方向。我感兴趣的方向是上、下、左和右。我的矩形由 Cell 类表示。我正在尝试在该单元类中编写一个函数。函数接受 Cell 类型的参数,将传递的单元格 w.r.t 的方向返回到调用单元格的 1(up) 2(down) 3(left) 或 4(right)。
我尝试了什么 我找到了两个矩形的中点,然后比较了 x 和 y 坐标。但这种技术并非在所有情况下都有效。每当我发现一个缺失的案例时,我必须包含越来越多的 if 语句,我认为这不是一个好的编程习惯。它变得越来越容易出错且难以理解。
在寻找解决方案时:也许 math.atan2() 可以在我的情况下工作。也许我可以找到这两个矩形中点之间的角度,并使用角度值来确定方向。但我不确定我的想法是否正确。
请指导我。我应该继续使用我的函数并纠正它,还是有更好的解决方案,例如 math.atan2()?代码后显示了一个帮助图像,以便更好地理解和所需的解决方案。
代码
public int dirOfThisCell(Cell cell)
{
int dir = 0;
//find mid points of both cells
PointF midPointThis = this.computeAndGetMidPoint();
PointF midPointCell = cell.computeAndGetMidPoint();
//MessageBox.Show(mess);
//if x of both points is same or with little variance because of variance in sizes of cells
===>> //Comparison Starts!!
if (midPointThis.X > midPointCell.X)
{
//this cell is to the right.
if ((midPointCell.Y) == (midPointThis.Y))
{
dir = 3;
}
else if (Math.Abs(midPointCell.Y) - Math.Abs(midPointThis.Y) < 5) { dir = 3; }
else if (Math.Abs(midPointCell.Y) - Math.Abs(midPointThis.Y) > 5) {
if (midPointThis.Y > midPointCell.Y) { dir = 1; }
else if (midPointThis.Y < midPointCell.Y) dir = 2;
}
// a considerable difference
else { dir = 3; }
//some small variations in y
//else if(Math.Abs()
}
else if (midPointThis.X < midPointCell.X)
{
// this cell is to the left
if ((midPointCell.Y) == (midPointThis.Y))
{
dir = 4;
}
else if (Math.Abs(midPointCell.Y) - Math.Abs(midPointThis.Y) <= 10)
{
dir = 4;
}
}
//if this cell is below
else if (midPointThis.Y > midPointCell.Y)
{
//this cell is down than the cell
if ((midPointCell.X) == (midPointThis.X))
{
dir = 1;
}
//else if (Math.Abs(midPointCell.X) - Math.Abs(midPointThis.X) < 2) { dir = 1; }
}
else if (midPointThis.Y < midPointCell.Y)
{
if ((midPointCell.X) == (midPointThis.X))
{
dir = 2;
}
}
return dir;
}
图片
示例矩形按图片编号显示。矩形可以是单个单元格,也可以是由多个编号的单元格组合而成。
需要样品解决方案
- 单元格 18 w.r.t 到 8 的方向应该向上 (1)
- 单元格 18 w.r.t 到 10 的方向应该向上 (1)
- 单元格 14 w.r.t 到 13 的方向应该是正确的 (4)
- 单元格 9 w.r.t 到 31 的方向应向下 (1)
- 单元格 15 w.r.t 到 9 的方向应向左 (3)
我正在使用 c#。
任何帮助将不胜感激。
谢谢
【问题讨论】:
-
我不明白使用 Math.Abs 对您有何帮助。如果单元格位于左侧,则 X 为负值,如果位于当前单元格下方,则 Y 为负值。通过删除负数,您只是将位移(包括方向,这是您想要的)转换为距离(这是您不想要的)。
-
更不用说,您正在使用 int 来保存根据定义具有 2 个值的方向。如果一个单元格是向上的,那并不意味着它也没有离开。一个单元格既可以向左也可以向上。考虑使用具有水平方向 (horDir) 和垂直方向 (verDir) 的结构。
-
我的建议:在编写代码之前花更多的时间进行设计。当您想选择向上或向下与向左或向右时,精确计算。您甚至可以在纸上绘制一个示例网格,然后在单元格之间画线。如果线条从细胞质心到质心,很好。你的那种方向性方案在文献中有一个名字:“曼哈顿”。顺便说一句,您在示例解决方案中显示的第二个示例中显示的结果似乎不正确。单元 18 离单元 10 的东边比它的北边要远得多。答案不是“正确”而不是“向上”吗?
-
如果它确实是您正在寻找的一个方向。一旦你有了水平和垂直位移的值。将这些转换为绝对值,然后以较大者为准,例如如果 X 大于 Y,则使用 X 的相应方向作为最终结果。
-
@O.Jones 不,答案应该是“向上”。原因。我正在寻找相邻单元格的方向。考虑 10、9 和 8 形成一个矩形,那么 18 是方向应该向上的相邻单元格。
标签: c# geometry coordinates rectangles