问题描述
给出两个x,y,宽度,高度(以像素为单位)和旋转值(以度为单位)的矩形-如何计算它们的轮廓彼此之间的最接近距离?
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?
背景:在用Lua编写的游戏中,我正在随机生成地图,但要确保某些矩形彼此之间的距离不是太近-这是必需的,因为如果矩形之间的距离接近一定距离,则地图将无法解决位置,因为球需要在它们之间传递.速度不是一个大问题,因为我没有太多矩形,并且每个级别只生成一次地图.我在StackOverflow上找到的先前链接是 this 和此
Background: In a game written in Lua I'm randomly generating maps, but want to ensure certain rectangles aren't too close to each other -- this is needed because maps become unsolvable if the rectangles get into certain close-distance position, as a ball needs to pass between them. Speed isn't a huge issue as I don't have many rectangles and the map is just generated once per level. Previous links I found on StackOverflow are this and this
非常感谢!
推荐答案
不是在Lua中,这是基于M Katz的建议的Python代码:
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.
其中
-
dist
是点之间的欧式距离 - 矩形. 1由点
(x1, y1)
和(x1b, y1b)
组成 - 矩形. 2由点
(x2, y2)
和(x2b, y2b)
组成
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)
这篇关于如何计算两个矩形之间的距离? (上下文:Lua中的游戏.)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!