Как проверить наличие столкновений в Pygame - PullRequest
1 голос
/ 19 апреля 2020

Я пытался заставить некоторый код работать, когда два ящика сталкиваются друг с другом в 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()

1 Ответ

0 голосов
/ 19 апреля 2020

Я рекомендую использовать 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()
...