c++ - SFML 的 'intersects' 函数总是返回 'true'

标签 c++ sfml

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

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

}

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

从图中可以看出,左边的 Racket 和小球并没有靠得很近,但是控制台还是说它们重叠了。这里发生了什么,你如何解决这个问题?

编辑:我尝试用刚好足够的代码制作一个测试项目来重现问题。从两个矩形的位置来看,我们可以看出它们绝对没有相交。但是,它仍然说它们相互重叠。

#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;

最佳答案

getLocalBounds() 的文档说

The returned rectangle is in local coordinates, which means that it ignores the transformations (translation, rotation, scale, ...) that are applied to the entity. In other words, this function returns the bounds of the entity in the entity's coordinate system.

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

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

关于c++ - SFML 的 'intersects' 函数总是返回 'true',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49085300/

相关文章:

c++ - SFML 的 std::bad_alloc 错误

shader - SFML 着色器制服 : passing my own class

c++ - 使用 CMake 编译 SFML 应用程序

c++ - 子进程和父进程异步通信linux

c# - 将对象数组从 C# 返回到 COM 中的 C

c++ - BOOST_FOREACH 在模板中不起作用?

c++ - Blackmagic 帧 : convert from yuv to RGB to use in openCV

c++ - 我怎么知道谁拥有某个指针

c++ - "Unable to open file libc++abi.dylib"。程序构建,但在运行时崩溃。使用 xcode 10.1 (10B61)

c++ - 使用 SFML 资源管理器的 C++ 模板