SFML的'intersects'函数总是返回'true'

问题描述 投票:0回答:1

我想知道两个矩形是否使用SFML相互重叠。这是我的代码:

if (ball.getLocalBounds().intersects(paddle.getLocalBounds()))
{
    //perform action

}

如果两个矩形相互重叠,代码将执行操作。但不知何故,它总是在每种情况下返回true,即使在两个矩形甚至没有相互交叉的情况下,例如:

从图中可以看出,左桨和球甚至没有彼此靠近,但控制台仍然说它们彼此重叠。这里发生了什么,你如何解决这个问题?

编辑:我尝试使用足够的代码制作一个测试项目来重现问题。从两个矩形的位置,我们可以看到它们绝对不会相互交叉。但是,它仍然表示它们相互重叠。

#include <SFML\Graphics.hpp>
#include <iostream>

using namespace std;
using namespace sf;

int main()
{

RenderWindow window(VideoMode(800, 600), "Test", Style::Close);

RectangleShape r1 = RectangleShape(Vector2f(100, 100));
RectangleShape r2 = RectangleShape(Vector2f(100, 100));

r1.setPosition(0, 0);
r2.setPosition(700, 500);

while (window.isOpen())
{
    Event e;

    while (window.pollEvent(e))
    {
        if (e.type == Event::Closed)
        {
            window.close();
        }
    }

    cout << r1.getLocalBounds().intersects(r2.getLocalBounds()) << endl;

    window.clear();

    window.draw(r1);
    window.draw(r2);

    window.display();
}

return 0;

}

c++ sfml
1个回答
3
投票

getLocalBounds()的文档说

返回的矩形位于本地坐标中,这意味着它忽略了应用于实体的变换(平移,旋转,缩放......)。换句话说,此函数返回实体坐标系中实体的边界。

这让您了解两个矩形始终重叠的原因。全局(x: 300, y: 300, w: 500, h: 400)矩形将是(x: 0, y: 0, w: 500, h: 400)在其自己的坐标系中。

你的两个边界都从(x: 0, y: 0)开始,因此它们总是相交。

© www.soinside.com 2019 - 2024. All rights reserved.