如何在 Pygame 中检查碰撞

问题描述 投票:0回答:1

我试图在 Pygame 中两个盒子相互碰撞时运行一些代码,但不知何故它不起作用。

游戏声明

class coin:
def __init__(self, x, y, height, width):
    self.x = x
    self.y = y
    self.x2 = x + width
    self.y2 = y + height
    self.height = height
    self.width = width
x = 50
y = 50
width = 20
height = 20
x2 = x + width
y2 = y + height
vel = 10
newCoin = coin(0,0,0,0)
needCoin = True

def generateCoin():
    randX = math.floor(random.random() * 100)
    randY = math.floor(random.random() * 100)
    print(randX)
    print(randY)
    return coin(randX, randY, 10, 10)

游戏展示

if ((x < newCoin.x2) and (newCoin.x < x2) and (y2 > newCoin.y) and (newCoin.y2 > y)):
        print("Colliding")
        needCoin = True
        pygame.time.delay(100)

    pygame.draw.rect(win, (0,255,0), (newCoin.x,newCoin.y,newCoin.width,newCoin.height))
    pygame.display.update()
python pygame 2d
1个回答
0
投票

我建议使用

pygame.Rect
.coliderect()
:

coin_rect = pygame.Rect(newCoin.x, newCoin.y, newCoin.width, newCoin.height)
rect_2 = pygame.Rect(x, y, width, height)

if coin_rect.colliderect(rect_2):
    print("Colliding")
    needCoin = True
    pygame.time.delay(100) 

如果您想让代码正常工作,那么您必须确保

self.x2
self.y2
分别为
x2
y2
是最新的。当
self.x
self.y
分别
x
y
发生变化时,您必须更新此变量。


无论如何,我建议使用

pygame.Rect
代替
x
y
width
height

class coin:
    def __init__(self, x, y, height, width):
        self.rect = pygame.Rect(x, y, height, width)

def generateCoin():
    randX = math.floor(random.random() * 100)
    randY = math.floor(random.random() * 100)
    print(randX)
    print(randY)
    return coin(randX, randY, 10, 10)

test_rect = pygame.Rect(50, 50, 20, 20)
vel = 10
newCoin = generateCoin()
needCoin = True
if newCoin.rect.colliderect(test_rect):
    print("Colliding")
    needCoin = True
    pygame.time.delay(100)

pygame.draw.rect(win, (0,255,0), newCoin.rect)
pygame.display.update()
© www.soinside.com 2019 - 2024. All rights reserved.