C# intersects problem

Associate
Joined
14 Apr 2003
Posts
1,101
Hi,

I have two rectangles with coords as follows:

Rectangle 1:
Top left = (10, 0 )
bottom Right = (621, -457)

Rectangle 2:
Top left = (0, 0)
bottom right = (1024, -1024)

now that appears to me as if they are intersecting, however, when i do the intersectsWith method of either rectangle, passing in the other rectangle as a parameter it returns false.


Am i doing something wrong or is it a bug?

UPDATE: It seems to be a problem with having a minus height for my rectangles, is there any way round this?
 
Last edited:
Its very unlikely to be a bug, the libraries are excellent.

Are you sure you are creating the rectangles properly? Maybe you are thinking the constructor is
public Rectangle ( int x1, int y1, int x2, int y2)
when infact it is
public Rectangle ( int x, int y, int width, int height )
.
I would guess that width and height always have to be positive and that x and y must specify the top left hand corner of the rectangle. Only a guess though.
 
If it is a problem with having negative co-ordinates in there then you could try applying a matrix transform to the graphics object to generate a co-ordinate system where you can use positive values for the points of your rectangles?
 
OK, I'm home from work now so I fired up Reflector and it turns out this is the code for the IntersectsWith method

Code:
public bool IntersectsWith(Rectangle rect)
{
      if (((rect.X < (this.X + this.Width)) && (this.X < (rect.X + rect.Width))) && (rect.Y < (this.Y + this.Height)))
      {
            return (this.Y < (rect.Y + rect.Height));
      }
      return false;
}

In your case as you have a negative height the third condition [rect.Y < (this.Y + this.Height)] isn't being satisfied.

I suppose you can either create a new class which inherits from Rectangle and override the method if you really are insistent on a negative height

Also, if you are using the following to create your rectangles:

Code:
Rectangle r = new Rectangle(10, 0, 521, -457)

You should be able to replace it with

Code:
Rectangle r = new Rectangle(10, 457, 521, 457)

and the method will work. I would recommend this as it makes no sense to have a negative height.

PS If any of you don't know about Reflector and are .NET programmers I strongly urge you to download it (it's free too) as it is very helpful for giving an insight into the framework.
http://www.aisto.com/roeder/dotnet/
 
yeah, i worked out it was a problem with negative height/width values so ive converted them all to positive, just had to rework a bit of code so wondered if there was another way round it, being lazy!!

thanks for the info and ill be sure to down load that proggy

cheers,

matt
 
Back
Top Bottom