我正在使用hitboxes玩游戏并最终得到以下数据:
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);
此检查是否会留下任何可能无法正常工作的星座?
答案 0 :(得分:1)
在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);