import math
def collision(rleft, rtop, width, height, # rectangle definition
center_x, center_y, radius): # circle definition
""" Detect collision between a rectangle and circle. """
# complete boundbox of the rectangle
rright, rbottom = rleft + width/2, rtop + height/2
# bounding box of the circle
cleft, ctop = center_x-radius, center_y-radius
cright, cbottom = center_x+radius, center_y+radius
# trivial reject if bounding boxes do not intersect
if rright < cleft or rleft > cright or rbottom < ctop or rtop > cbottom:
return False # no collision possible
# check whether any point of rectangle is inside circle's radius
for x in (rleft, rleft+width):
for y in (rtop, rtop+height):
# compare distance between circle's center point and each point of
# the rectangle with the circle's radius
if math.hypot(x-center_x, y-center_y) <= radius:
return True # collision detected
# check if center of circle is inside rectangle
if rleft <= center_x <= rright and rtop <= center_y <= rbottom:
return True # overlaid
return False # no collision detected
import math
def dist(p1, p2, c):
x1,y1 = p1
x2,y2 = p2
x3,y3 = c
px = x2-x1
py = y2-y1
something = px*px + py*py
u = ((x3 - x1) * px + (y3 - y1) * py) / float(something)
if u > 1:
u = 1
elif u < 0:
u = 0
x = x1 + u * px
y = y1 + u * py
dx = x - x3
dy = y - y3
dist = math.sqrt(dx*dx + dy*dy)
return dist
下面是一个测试:
rect = [[0. , 0. ],
[ 0.2, 1. ],
[ 2.2, 0.6],
[ 2. , -0.4]]
c = 0.5, 2.0
r = 1.0
distances = [dist(rect[i], rect[j], c) for i, j in zip([0, 1, 2, 3], [1, 2, 3, 0])]
print distances
print any(d < r for d in distances)
以下是我在评论中所描述的内容,加上修改以正确处理Michael Anderson在评论中指出的大矩形内的圆:
对于这种碰撞检测,您有两个常用选项。
首先是了解两个二维对象碰撞的方式。
从技术上讲,案例1。只有在情况2时才能发生。也会发生,但这通常是一种更便宜的支票。 在同时检查两个对象顶点的情况下,情况3由情况1检查。
我想这样继续。(按便宜程度排列)
第二种也是更普遍的方法是基于形状的乘积/展开的概念。 此操作允许您将交叉点问题转换为点包含问题。
在这种情况下,圆/矩形框的交点可以替换为选中圆角矩形中的点。
使用Shortest distance between a point and a line segment中的
dist
函数下面是一个测试:
输出:
下面是情节:
相关问题 更多 >
编程相关推荐