Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: How to check whether rectangle intersect with Line ?  (Read 3897 times)

0 Members and 1 Guest are viewing this topic.

lyvinhloi.cntt

  • Newbie
  • *
  • Posts: 10
    • View Profile
    • Email
How to check whether rectangle intersect with Line ?
« 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

Geheim

  • Full Member
  • ***
  • Posts: 201
    • View Profile
    • Email
Re: How to check whether rectangle intersect with Line ?
« Reply #1 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 with each line, which would give you the intersection points too ;)
Failing to succeed does not mean failing to progress!

jannugimes

  • Guest
Re: How to check whether rectangle intersect with Line ?
« Reply #2 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

lyvinhloi.cntt

  • Newbie
  • *
  • Posts: 10
    • View Profile
    • Email
Re: How to check whether rectangle intersect with Line ?
« Reply #3 on: May 19, 2014, 05:07:44 pm »
Haha ... I'm idiot >.< Just thinking in another side ^^
Ok thanks guys, problem solved...