gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:44:33 25 4
gpt4 key购买 nike

在这里,我将两个图像一碰撞就卡住。 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/

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