gpt4 book ai didi

python - 检测矩形与圆的碰撞

转载 作者:太空宇宙 更新时间:2023-11-04 09:01:39 25 4
gpt4 key购买 nike

我有一个带有中心点 (Center_X, Center_Y) 的圆,我正在检测一个矩形是否落入它的半径 (Radius)。我将如何执行此任务?我试过使用

if (X - Center_X)^2 + (Y - Center_Y)^2 < Radius^2:
print(1)

然后我试着画一个圆圈来覆盖这个区域:

Circle = pygame.draw.circle(Window, Blue, (Center_X, Center_Y), Radius, 0)

但是好像不排队。我做错了什么吗?

最佳答案

这是我在评论中描述的内容,以及迈克尔·安德森 (Michael Anderson) 在评论中指出的对较大矩形内圆圈情况的正确处理的更改:

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

关于python - 检测矩形与圆的碰撞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24727773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com