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

后端 未结 8 1528
梦毁少年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

    Not in Lua, a Python code based on M Katz's suggestion:

    def rect_distance((x1, y1, x1b, y1b), (x2, y2, x2b, y2b)):
        left = x2b < x1
        right = x1b < x2
        bottom = y2b < y1
        top = y1b < y2
        if top and left:
            return dist((x1, y1b), (x2b, y2))
        elif left and bottom:
            return dist((x1, y1), (x2b, y2b))
        elif bottom and right:
            return dist((x1b, y1), (x2, y2b))
        elif right and top:
            return dist((x1b, y1b), (x2, y2))
        elif left:
            return x1 - x2b
        elif right:
            return x2 - x1b
        elif bottom:
            return y1 - y2b
        elif top:
            return y2 - y1b
        else:             # rectangles intersect
            return 0.
    

    where

    • dist is the euclidean distance between points
    • rect. 1 is formed by points (x1, y1) and (x1b, y1b)
    • rect. 2 is formed by points (x2, y2) and (x2b, y2b)

提交回复
热议问题