简体   繁体   English

求一个矩形的面积是否与另一个相交的实现问题

[英]Problem with the implementation of finding whether the area of a rectangle intersects another

I am trying to implement a method which returns true if some part of the area covered by a rectangle is also part of another rectangle, false otherwise using the x and y coordinates along with the width and height.我正在尝试实现一个方法,如果矩形覆盖的区域的某些部分也是另一个矩形的一部分,则返回 true,否则返回 false,否则使用 x 和 y 坐标以及宽度和高度。

Along with the code below, I've initialised the variables x,y,width and height which are attributes of the object BoundingBox连同下面的代码,我已经初始化了变量 x、y、width 和 height,它们是对象 BoundingBox 的属性

public boolean intersects(BoundingBox box) {
    int boxx = getX();
    int boxy = getY();
    int boxw = getWidth();
    int boxh = getHeight();
    if ( box.getX()+ box.getWidth() < boxx || box.getY() + box.getHeight() < boxy || boxx+boxw < box.getX() || boxy + boxh < box.getY()) {
        if (boxw*boxh <= box.getWidth()*box.getHeight()) {
            return false;
        }
        else {
            return true;
        }
    }   
    else {
        return true;
    }
}

When I try to see if a rectangle with (x,y,width,height) = (20,0,1,20) intersects with the original rectangle I've set up as (10,10,10,10), I expected to see the result of false but the actual output is true?当我尝试查看 (x,y,width,height) = (20,0,1,20) 的矩形是否与我设置为 (10,10,10,10) 的原始矩形相交时,我预期会看到 false 结果但实际输出为 true?

Use this in your for loop.在您的 for 循环中使用它。

if (boxx > box.getX()+box.getWidth() || box.getX(0) > boxx) { 
    return false; 
}

if (boxy < box.getY()+box.getHeight() || box.getY() < boxy+boxh) { 
    return false; 
} 
return true; 

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

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