简体   繁体   English

矩形重载方法问题

[英]Rectangle overloaded method issue

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. 因此,我有一个用于弹跳框的矩形。我要弹跳该矩形的球,因此需要能够检查它是否从矩形的x轴或y轴弹起。 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: .X和.Y值显然可以用作Visual Studio,因为我在键入代码时会自动将它们调出,但是在放置它们之后,我会得到以下错误:

The best overloaded method match for 最佳重载方法匹配

'Microsoft.Xna.Framework.Rectangle.Intersects(Microsoft.Xna.Framework.Rectangle)' has some invalid arguments. 'Microsoft.Xna.Framework.Rectangle.Intersects(Microsoft.Xna.Framework.Rectangle)'具有一些无效的参数。

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? 显然,我以错误的方式使用了原型,相反,有人对我如何检测矩形是否与X轴或Y轴相交有任何提示吗?

Thanks. 谢谢。

The prototype is: 原型是:

Rectangle.Intersects(Rectangle rect)

but you are trying to feed it an integer, which is not a rectangle. 但您尝试将其输入一个整数,而不是矩形。

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) . 然后,您将能够在每个实例上调用方法: 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. 请注意,您需要区分需要对单个点(X或Y)进行哪种类型的交点,因此最好使用这样的方法名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM