1

所以我试图找出一个点是否包含在一个矩形内。当矩形的高度和宽度都是正数或负数但不是只有一个是负数时,它可以正常工作。具有负宽度或高度的矩形的整个想法有点奇怪,但当它们都是负值时,它似乎处理得很好。所以我想知道 XNA 在这种情况下如何处理 contains 方法?如果它不起作用,它不应该在这种情况下不接受它。

我用它来创建一个 rts 样式选择框,只是为了定义那个矩形,这样我就可以知道里面有什么。这是我的代码:

if (InputHandler.IsLeftMouseHeld() == true)
{
    selectionBoxRectangle = new Rectangle(selectionBoxRectangle.X,
      selectionBoxRectangle.Y,
      (int)Vector2.Transform(InputHandler.MousePosition(),
      Matrix.Invert(camera.Transformation)).X - selectionBoxRectangle.X,
      (int)Vector2.Transform(InputHandler.MousePosition(),
      Matrix.Invert(camera.Transformation)).Y - selectionBoxRectangle.Y);

    foreach(ControllableCharacter character in characters.OfType<ControllableCharacter>())
    {
        if (selectionBoxRectangle.Contains(character.DestRectangle.Center) == true
          || character.DestRectangle.Contains(selectionBoxRectangle))
        {
            character.Selected = true;
            character.Color = Color.LightGreen;
        }
        else
        {
            character.Selected = false;
            character.Color = Color.White;
        }
    }
}

在这种情况下如何处理它的任何想法?

4

3 回答 3

1

如果你反编译 Rectangle 的 XNA 代码,你可以在这里看到实现:

public bool Contains(Point value)
{
    return this.X <= value.X && value.X < this.X + this.Width && this.Y <= value.Y && value.Y < this.Y + this.Height;
}
于 2012-12-17T19:36:21.630 回答
1

如果您像我一样懒惰,这是可以提供帮助的扩展方法

public static bool ContainsExt(this RectangleF rect, PointF point)
{
    bool widthOk;
    bool heightOk;

    if (rect.Width < 0)
    {
        widthOk = rect.X >= point.X && point.X > rect.X + rect.Width;
    }
    else
    {
        widthOk = rect.X <= point.X && point.X < rect.X + rect.Width;
    }

    if (rect.Height < 0)
    {
        heightOk = rect.Y >= point.Y && point.Y > rect.Y + rect.Height;
    }
    else
    {
        heightOk = rect.Y <= point.Y && point.Y < rect.Y + rect.Height;
    }

    return widthOk && heightOk;
}
于 2020-08-20T12:37:30.777 回答
0

您始终可以编写自己的方法,该方法比默认方法更适用于特殊情况。

像这样:

bool RectangleContainsPoint(Rectangle rect, Point p)
{
    if (rect.Width < 0 && rect.Height >=0 ||
        rect.Width >=0 && rect.Height < 0)  // if in this case you have problems

        return MyImplementationOfContains(rect, p);
    else
        return Rectangle.Contains(rect, p);
}

bool MyImplementationOfContains(Rectangle rect, Point p)
{
    // as the name of this method suggests, your implementation
}
于 2012-12-17T20:32:16.037 回答