Reputation: 1
Basically I have a grid of rectangles, 75x75 each, side by side. 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.
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 =)
Upvotes: 0
Views: 659
Reputation: 1317
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
Upvotes: 0
Reputation: 1662
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. 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.
Considering your example shows just a list of rectangles, I'm guessing your 2D map is actually just a one dimensional array. Which you can index into by [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.
Upvotes: 0
Reputation: 614
If all rectangles are the same size, you could just take center of it, the center of which you want to check intersetcion, measure length between two points and do the same with other rectangle.
Upvotes: 3