如何计算两个矩形之间的距离?(上下文:Lua 中的游戏.) [英] How to calculate distance between two rectangles? (Context: a game in Lua.)

查看:35
本文介绍了如何计算两个矩形之间的距离?(上下文:Lua 中的游戏.)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定两个矩形,它们的 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

非常感谢!

推荐答案

Not in 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 中的游戏.)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆