Search code examples
2d-gamescollision

How do I detect triangle and rectangle intersection?


I am developing an Android game and I would like to know how to detect the collision of a rectangle knowing its position (x and y), width and height and a triangle knowing x,y, width and height. Triangles are always right triangles as the result of dividing a rectangle through its diagonal so the (x,y) parameter will be a position in the hypotenuse, not the center of the triangle. Any help would be appreciated!


Solution

  • I´ve finally done this using the function intersect for two lines. Lines are defined with initial point (x,y) and final point (x,y)

    // a1 is line1 start, a2 is line1 end, b1 is line2 start, b2 is line2 end
     static boolean intersects(Vector2 a1, Vector2 a2, Vector2 b1, Vector2 b2)
    {
        Vector2 intersection = Vector2.Zero();
    
        Vector2 b = Vector2.Subtract(a2,a1);
        Vector2 d = Vector2.Subtract(b2,b1);
        float bDotDPerp = b.getX() * d.getY() - b.getY() * d.getX();
    
        // if b dot d == 0, it means the lines are parallel so have infinite intersection points
        if (bDotDPerp == 0)
            return false;
    
        Vector2 c = Vector2.Subtract(b1,a1);
        float t = (c.getX() * d.getY() - c.getY() * d.getX()) / bDotDPerp;
        if (t < 0 || t > 1)
            return false;
    
        float u = (c.getX() * b.getY() - c.getY() * b.getX()) / bDotDPerp;
        if (u < 0 || u > 1)
            return false;
    
        intersection = Vector2.Sum(a1,Vector2.Multiply(b,t));
    
        return true;
    }
    

    To know if a triagle intersects a rectangle you check the intersection of every line from the triangle with every line from the rectangle with function above.