代码之家  ›  专栏  ›  技术社区  ›  Basti

精确检查两个双坐标矩形是否相交

  •  0
  • Basti  · 技术社区  · 7 年前

    我在玩Hitbox游戏,结果得到了以下数据:

    final double targetSmallestX = targetCenter.getX() - targetHalfWidth;
    final double targetSmallestY = targetCenter.getY() - targetHalfHeight;
    final double targetHighestX = targetCenter.getX() + targetHalfWidth;
    final double targetHighestY = targetCenter.getY() + targetHalfHeight;
    final double sourceSmallestX = sourceCenter.getX() - sourceHalfWidth;
    final double sourceSmallestY = sourceCenter.getY() - sourceHalfHeight;
    final double sourceHighestX = sourceCenter.getX() + sourceHalfWidth;
    final double sourceHighestY = sourceCenter.getY() + sourceHalfHeight;
    

    我要做的是检查,如果给定的两个矩形 target source 相互交叉。可以这样做

    Rectangle target = new Rectangle(targetSmallestX, target.width, targetSmallestY, target.height);
    Rectangle source = new Rectangle(sourceSmallestX, source.width, sourceSmallestY, source.height);
    target.intersect(source);
    

    但这需要我处理整数。
    对于这样一个看似简单的任务,我提出的所有算法似乎都太长太复杂了。有没有人想到一个聪明的方法来解决这个问题?

    编辑:
    当前方法

    (targetSmallestX < sourceSmallestX + this.width)
    && (sourceSmallestX < (targetSmallestX + target.width))
    && (targetSmallestY < sourceSmallestY + this.height)
    && (sourceSmallestY < targetSmallestY + target.height);
    

    该检查是否会留下任何可能无法正常工作的星座?

    1 回复  |  直到 7 年前
        1
  •  1
  •   k_ssb    7 年前

    在Java中,您可以使用 java.awt.geom.Rectangle2D 它以浮点精度表示坐标。准确地说,它的内部类 java.awt.geom.Rectangle2D.Double 使用 double 表示坐标。

    Rectangle2D target = new Rectangle2D.Double(targetSmallestX, targetSmallestY, target.width, target.height);
    Rectangle2D source = new Rectangle2D.Double(sourceSmallestX, sourceSmallestY, source.width, source.height);
    target.intersect(source);