Pygame图像碰撞在图像之间留下了视觉上的空白

2024-09-27 02:17:33 发布

您现在位置:Python中文网/ 问答频道 /正文

在这里,我冻结了两个图像,一旦他们碰撞。棒棒糖从左上角开始,熊从右下角开始。它们在中间碰撞。我的位置告诉我他们距离较近,距离不到50个点

以下是棒棒糖距离熊的坐标: lollipop[452, 320] and bear[448, 330]distance between the two: 10.742572683895418

为什么这些情节跟我看到的不一样?为什么棒棒糖的位置参考在图像的底部而熊在顶部?这是我如何blitting图像。在

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

图像尺寸分别为(50,50)和(100100)。在


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

Space between two images when they collided

下面是当棒棒糖从右边来,熊从左边来时,它们是如何碰撞的。enter image description here

下面是它们从上/下相撞lollipop[480, 291] bear[440, 261] distance: 49.491213409963144

enter image description here

如何检查碰撞:

^{pr2}$

Tags: andtherect图像距离positionbetweendistance
1条回答
网友
1楼 · 发布于 2024-09-27 02:17:33

如果我明白,你是在比较精灵的中心与精灵的大小。这对于矩形是不正确的。在

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

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

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

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实用程序。在

相关问题 更多 >

    热门问题