【问题标题】:Can't determine if two squares/rectangles are intersecting each other无法确定两个正方形/矩形是否相互交叉
【发布时间】:2020-10-14 10:48:20
【问题描述】:

作为我使用的在线图形:https://www.khanacademy.org/computer-programming/spin-off-of-rectx-y-width-height-radius/4975791745220608

矩形坐标:

矩形 1:x:180 y:30

矩形 2:x:160 y:30

我注意到的是,渲染从一个点开始,在 X 轴上按宽度增加,在 Y 轴按高度增加。所以我推断出以下几点:x1 和 y1 等于矩形坐标(x1 和 y1 是左上角),x2,y2 是右下角/坐标,它们等于平方坐标的总和,换句话说就是 x1和 y1 以及正方形的宽度和高度。

这是我写的代码:

#include <stdio.h>
#include <iostream>

struct A
{
    int x1, x2;
    int y1, y2;
};

struct B 
{
    int x1, x2;
    int y1, y2;
};

bool doOverlap(A a, B b)
{
    if (a.x1 < b.x2 && a.x2 > b.x1 &&
        a.y1 > b.y2 && a.y2 < b.y1)
        return true;

    return false;
}

int main()
{
    /* 
        Rectangle 1 coords: X: 180 Y: 30
        Rectangle 2 coords: X: 160 Y: 30
    */
    
    A a;
    B b;

    /* 
        The render begins from top left corner (that's our center and
        from here begins the render with +width on x and +heigth on y
        (correct me in case i'm wrong but that's what i noticed: https://imgur.com/a/nZKBB0m
        (as can you see in that photo, the white rectangle has l1: (x,y): 0 0)

        rectangles are 40x40
    */
    a.x1 = 180;
    a.y1 = 30;
    a.x2 = a.x1 + 40;
    a.y2 = a.y1 + 40;

    b.x1 = 160;
    b.y1 = 30;
    b.x2 = b.x1 + 40;
    b.y2 = b.y1 + 40;

    if (doOverlap(a, b))
    {
        std::cout << "y";
    }
    else
        std::cout << "n";
   
    return 0;
}

问题是它总是返回 false(检查了很多代码,但似乎没有一个代码在工作) 那么,我做错了什么?

【问题讨论】:

    标签: c++ geometry


    【解决方案1】:

    你只检查 a 是否在 b 之上,然后检查 a 是否在 b 的左边。 您需要检查 a 和 b 的 x 间隔是否重叠,然后检查 y 间隔是否重叠。这是一种方法:

    bool doOverlap(A a, B b)
    {
        if (a.x1 > b.x2 || b.x1 > a.x2)
            return false;
        if (a.y1 > b.y2 || b.y1 > a.y2)
            return false;
        return true;
    }
    

    第一个 if 检查 a 和 b 的 x 区间是否重叠,如果不重叠则返回 false。第二个对 y 间隔执行相同的操作。如果 x 和 y 间隔都重叠,则矩形重叠

    【讨论】:

      猜你喜欢
      • 2010-09-23
      • 1970-01-01
      • 2023-03-12
      • 2010-10-19
      • 2015-03-05
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多