[英]How to determine which rectangle is intersecting more C# XNA
Basically I have a grid of rectangles, 75x75 each, side by side. 基本上我有一个并排的矩形网格,每个矩形75x75。 I'm placing an object into these rectangles and when I place the object I need to figure out which rectangle it is intersecting with the MOST.
我将一个对象放置在这些矩形中,当我放置该对象时,我需要弄清楚它与MOST相交的矩形。
It would most likely look something like this: 它很可能看起来像这样:
private Rectangle placeObject(Vector2 cursorPosition)
{
Rectangle HolderRectangle;
Rectangle r1 = new Rectangle((int)cursorPosition.Position.X, (int)cursorPosition.Position.Y, 70, 70);
Foreach( Rectangle r in rectangles)
{
r2 = new Rectangle((int)r.Position.X, (int)r.Position.Y, 75,75)
if( r1.Intersects(r2))
{
//Check how much it intersects
//if it intersects more than the current holder Rectangle
//set HolderRectangle = r2
}
}
return HolderRectangle;
}
Is what I'm asking even possible? 我要问的甚至可能吗? If so how?
如果可以,怎么办? All reply's are appreciated =)
感谢所有回复=)
如果所有矩形的大小均相同,则可以取其中心,您要检查其中心,测量两个点之间的长度,并与其他矩形相同。
If this is just for placement in a grid you certainly don't have to iterate over all of the "rectangles" 如果这只是为了放置在网格中,那么您当然不必遍历所有“矩形”
You know the dimensions of the grid components, in this case 75x75. 您知道网格组件的尺寸,在这种情况下为75x75。 If you divide your X and Y position by 75 you know which grid element it belongs to, you'll have to account for an offset if your camera can scroll.
如果将X和Y位置除以75,就知道它属于哪个网格元素,并且如果相机可以滚动,则必须考虑偏移量。
Considering your example shows just a list of rectangles, I'm guessing your 2D map is actually just a one dimensional array. 考虑到您的示例仅显示了一个矩形列表,我想您的2D地图实际上只是一维数组。 Which you can index into by
[y * numRectsPerRow + x]
您可以通过
[y * numRectsPerRow + x]
进行索引
I don't know the background of your project, but I'm guessing you won't want to keep your grid represented by a bunch of rectangles for long. 我不知道您的项目的背景,但我想您不想长时间将您的网格保持为一堆矩形。
I believe what you are looking for is the area of an overlapping rectangles. 我相信您要寻找的是重叠的矩形区域。
See this thread: 看到这个线程:
What is an Efficient algorithm to find Area of Overlapping Rectangles 查找重叠矩形区域的有效算法是什么
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.