How to calculate distance between two rectangles? (Context: a game in Lua.)

后端 未结 8 1510
梦毁少年i
梦毁少年i 2020-12-15 17:53

Given two rectangles with x, y, width, height in pixels and a rotation value in degrees -- how do I calculate the closest distance of their outlines toward each other?

相关标签:
8条回答
  • 2020-12-15 18:32

    Pseudo-code:

    distance_between_rectangles = some_scary_big_number;
    For each edge1 in Rectangle1:
        For each edge2 in Rectangle2:
            distance = calculate shortest distance between edge1 and edge2
            if (distance < distance_between_rectangles)
                distance_between_rectangles = distance

    0 讨论(0)
  • 2020-12-15 18:34

    Actually there is a fast mathematical solution.

    Length(Max((0, 0), Abs(Center - otherCenter) - (Extent + otherExtent)))
    

    Where Center = ((Maximum - Minimum) / 2) + Minimum and Extent = (Maximum - Minimum) / 2. Basically the code above zero's axis which are overlapping and therefore the distance is always correct.

    It's preferable to keep the rectangle in this format as it's preferable in many situations ( a.e. rotations are much easier ).

    0 讨论(0)
提交回复
热议问题