Rectangle overloaded method issue

152 Views Asked by At

So I have a rectangle I am using for a bouncing box.. I'm bouncing balls of this rectangle so need to be able to check if it is bouncing off either the x or y axis of my rectangle. Originally I had the code following code which was fine for generally detecting two objects colliding:

if (ballRect.Intersects(boxRect)
{

}

But now I want to change it so I can perform different actions depending on the axis of the rectangle so I tried this...

if (ballRect.Intersects(boxRect.X)
{
//perform action
}

if (ballRect.Intersects(boxRect.Y)
{
//perform different action
}

The .X & .Y values obviously can be used as visual studio automatically bring them up whilst I'm typing the code however after putting them I then get the following error:

The best overloaded method match for

'Microsoft.Xna.Framework.Rectangle.Intersects(Microsoft.Xna.Framework.Rectangle)' has some invalid arguments.

Why is this?

EDIT:

Clearly I'm using the prototype in the incorrect way, instead does anybody have any tips of how I would go about detecting if the rectangle is being intersected by the X or Y axis?

Thanks.

2

There are 2 best solutions below

2
On

The prototype is:

Rectangle.Intersects(Rectangle rect)

but you are trying to feed it an integer, which is not a rectangle.

0
On

You need to create a method for that. I usually create an extensions class for each type I need to extend. For you case it would be something like that:

public static class RectangleExtensions
{
    public static bool IntersectsOnX(this Rectangle rect, int xPoint)
    {
        return rect.Left <= xPoint && xPoint <= rect.Right;
    }
    public static bool IntersectsOnY(this Rectangle rect, int yPoint)
    {
        return rect.Top <= yPoint && yPoint <= rect.Bottom;
    }
}

Then, you'll just be able to invoke the methods on each instance: ballRect.IntersectsOnX(boxRect.X).

Please note that you need to distinguish what kind of intersection you need to do with a single point (X or Y), so it's better to have method names that say that.