Searching through the forums I found a function that checks whether two lines collide. Originally written by a member of these forums, Disch, here's a slightly altered version that I use in my project:
float PerpDot(const sf::Vector2f& a, const sf::Vector2f& b) { return (a.y*b.x) - (a.x*b.y); }
bool LineCollision(const sf::Vector2f& A1, const sf::Vector2f& A2, const sf::Vector2f& B1, const sf::Vector2f& B2, sf::Vector2f* out)
{
sf::Vector2f a(A2 - A1);
sf::Vector2f b(B2 - B1);
sf::Vector2f c(B2 - A2);
float f = PerpDot(a, b);
// lines are parallel
if (!f) { return false; }
float aa = PerpDot(a, c);
float bb = PerpDot(b, c);
std::cout << bb << std::endl;
if (f < 0)
{
if (aa > 0) return false;
if (bb > 0) return false;
if (aa < f) return false;
if (bb < f) return false;
}
else
{
if (aa < 0) return false;
if (bb < 0) return false;
if (aa > f) return false;
if (bb > f) return false;
}
if (out) { *out = b * (1.0f - (aa / f)) + B1; } // assigns the point of intersection
return true;
}
I have a request, since I am mathematically impaired
, could someone tell me how to change this function so that it checks whether a line intersects a rectangle instead? Currently I convert my rectangle shapes to 4 lines and check each line with the function, but I imagine there must be an easier way to do it?