Knowing two points of a rectangle, how can I figure out the other two?

前端 未结 9 1131
刺人心
刺人心 2021-01-05 01:47

Hey there guys, I\'m learning processing.js, and I\'ve come across a mathematical problem, which I can\'t seem to solve with my limited geometry and trigonometry knowledge o

9条回答
  •  悲&欢浪女
    2021-01-05 02:17

    There's a difference between a "quadrilateral" and a "rectangle".

    If you have the midpoint of the top and bottom, and the sides lengths, the rest is simple.

    Given:

    (x1, y1) -- (top_middle_x, top_middle_y) -- (x2, y1)
    
    (x1, y2) -- (btm_middle_x, btm_middle_y) -- (x2, y2)
    

    and top/bottom length along with right/left length.

    x1 = top_middle_x - top/bottom_length / 2; x2 = x1 + top/bottom_length;

    y1 = top_middle_y y2 = bottom_middle_y

    Obviously, that's the simplest case and assuming that the line of (tmx, tmy) (bmx, bmy) is solely along the Y axis.

    We'll call that line the "mid line".

    The next trick is to take the mid line, and calculate it's rotational offset off the Y axis.

    Now, my trig is super rusty.

    dx = tmx - bmx, dy = tmy - bmy.

    So, the tangent of the angle is dy / dx. The arctangent(dy / dx) is the angle of the line.

    From that you can get your orientation.

    (mind, there's some games with quadrants, and signs, and stuff to get this right -- but this is the gist of it.)

    Once you have the orientation, you can "rotate" the line back to the Y axis. Look up 2D graphics for the math, it's straight forward.

    That gets you your normal orientation. Then calculate the rectangles points, in this new normal form, and finally, rotate them back.

    Viola. Rectangle.

    Other things you can do is "rotate" a line that's half the length of the "top" line to where it's 90 deg of the mid line. So, say you have a mid line that's 45 degrees. You would start this line at tmx, tmy, and rotate this line 135 degrees (90 + 45). That point would be your "top left" corner. Rotate it -45 (45 - 90) to get the "top right" point. Then do something similar with the lower points.

提交回复
热议问题