python - Pygame 图像碰撞在视觉上留下图像之间的间隙

标签 python graphics pygame collision-detection

在这里,我将两个图像一碰撞就卡住。 Lollipop 从左上角开始,小熊从右下角开始。他们在中间碰撞。我的位置告诉我,他们的距离更近了,不到50点

以下是 Lollipop 到熊的坐标距离: Lollipop [452, 320] 和熊[448, 330] 两者之间的距离:10.742572683895418

为什么情节告诉我的与我所看到的不同?为什么 Lollipop 的位置引用位于图像的底部,而熊位于图像的顶部?这是我如何位图传输图像。

rect = surface1.get_rect()
rect = rect.move(position[0]-rect.width//2, position[1]-rect.height//2)
screen.blit(surface1, rect)

图像的尺寸分别为(50,50)和(100,100)。

<小时/>

如何让我的图像碰撞得比现在更近? (当蓝色背景接触时)

Space between two images when they collided

下面是当 Lollipop 从右侧来而从左侧来时它们如何碰撞。 enter image description here

这是它们从顶部/底部过来时如何碰撞 Lollipop [480, 291] 熊[440, 261] 距离:49.491213409963144

enter image description here

如何检查冲突:

def distance(p, q):
return math.sqrt((p[0]-q[0])**2 + (p[1]-q[1])**2)

最佳答案

如果我理解的话,您正在尝试将 Sprite 中心之间的距离与其中一个 Sprite 的大小进行比较。这对于矩形来说是不正确的。

首先,您使用的公式适用于圆。在这种情况下,您必须将距离与圆的组合半径进行比较。

对于矩形,您可以通过执行 Separating Axis Test 的最小形式来计算交集。 .

计算每个 Sprite 的最小和最大xy边界,并将它们与每个 Sprite 的组合半尺寸进行比较:

halfWidthSprite1 = sprite1.width//2
halfWidthSprite2 = sprite2.width//2
halfHeightSprite1 = sprite1.height//2
halfHeightSprite2 = sprite2.height//2
distanceX = abs(sprite1.center[0] - sprite2.center[0])
distanceY = abs(sprite2.center[1] - sprite2.center[1])

collision = (distanceX < (halfWidthSprite1 + halfWidthSprite2)) and
            (distanceY < (halfHeightSprite1 + halfHeightSprite2))

正如评论中提到的,您还可以使用内置 pygame.sprite.collide_rect实用程序。

关于python - Pygame 图像碰撞在视觉上留下图像之间的间隙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19826589/

相关文章:

python - 如何在 python 中更改现有第 3 方库中的函数

python - 如何让 BASH 脚本作为进程运行?这样即使 Python 脚本被杀死,BASH 脚本也会永远运行?

python - 如何评估文件是否已关闭?

visual-studio - Crystal 报表和 WMF 图像

python - 放大 pygame 中的窗口导致滞后

python - 在较小表面内移动表面不会显示以前隐藏的组件

python - 为 python 中的进程编写内核模式分析器

r - 在基本图形 R 中的特定面板周围绘制一个矩形

java - 如何用Java2D绘制内线

python - 无法通过按键盘上的 Q 键来结束游戏