SFML community forums

Help => Graphics => Topic started by: lyvinhloi.cntt on May 18, 2014, 12:17:51 pm

Title: How to check whether rectangle intersect with Line ?
Post by: lyvinhloi.cntt on May 18, 2014, 12:17:51 pm
Ok I have this code:
#include <iostream>
#include <SFML/Graphics.hpp>

int main(void)
{
//    sf::RenderWindow window(sf::VideoMode(800,600),"Testing");
//    window.setFramerateLimit(60);

    sf::VertexArray line(sf::Lines,2);
    line[0].position = sf::Vector2f(200,300);
    line[1].position = sf::Vector2f(600,300);

    sf::Rect<float> rect2(line.getBounds());
    sf::Rect<float> rect(200,100,300,200);

    sf::VertexArray drawrect(sf::Quads,4);
    drawrect[0].position = sf::Vector2f(100,200);
    drawrect[1].position = sf::Vector2f(400,200);
    drawrect[2].position = sf::Vector2f(400,400);
    drawrect[3].position = sf::Vector2f(100,400);

//    while (window.isOpen())
//    {
//        window.clear(sf::Color::Black);
//        window.draw(line);
//        window.draw(drawrect);
//        window.display();
//    }
    std::cout << rect.intersects(rect2);
}
 
You can uncomment to see what I have createn.
When I run this code, it always show 0 which mean there aren't intersection. But I think it should be 1, why not ?
If I were wrong, how to correct it ? I mean .. [ the title ] :D
Title: Re: How to check whether rectangle intersect with Line ?
Post by: Geheim on May 18, 2014, 01:43:20 pm
In your example it always returns false, because the height of your bounding box of the line is 0.
A workaround to this would be to set the width/height to 1 if it is 0.

However you could also make 4 lines out of the rectangle and check for line-line-intersection (http://en.wikipedia.org/wiki/Line%E2%80%93line_intersection) with each line, which would give you the intersection points too ;)
Title: Re: How to check whether rectangle intersect with Line ?
Post by: jannugimes on May 19, 2014, 09:00:23 am
There is one case that is not handled by the idea given by @templatetypedef: the case where the two endpoints of the line segment are inside the rectangle. But that case is easy to check: x1 < x3 && x3 < x2 && y1 < y3 && y3 < y2
Title: Re: How to check whether rectangle intersect with Line ?
Post by: lyvinhloi.cntt on May 19, 2014, 05:07:44 pm
Haha ... I'm idiot >.< Just thinking in another side ^^
Ok thanks guys, problem solved...