Search code examples
javamathposition

How to find the corresponding subtriangle of a position inside a rectangle


I have a dynamic rectangle in which 4 subtriangles (t0-t3) are created (by adding the diagonals from the vertices). When given a certain x|y coordinate what is the fastest way to find the corresponding triangle?. The rectangle has a specific position and dimension. I only need the right "id" so not the vertices of the triangle, so for example in the graphic when p1 is given as position 0 should be returned, 3 at p2 and 2 at p3, ...

One possible solution of course would be to create the triangles and query if the point is contained in one of them, but it feels like a very complicated solution for something that simple. I also thought about creating a vector from the center and measuring the angle but it also seems complicated in a rectangle with varying dimensions.

Example Rectangle


Solution

  • Consider the following:

    Let the bottom left corner of the rectangle be (0,0) and the top right corner be (1,1). Now, the two lines that form the triangles are defined as:

    y = x and y = 1-x
    

    For every point except (.5,.5) we have a ternary conditional for a given x or y. For example, given that x = .2, we know that:

    if y < .2, we're in the bottom triangle (t2),
    elif .2 < y < .8, we're in the left triangle (t3),
    else, we're in the top triangle (t0).

    Hopefully this helps without explicitly giving you the code.