В Pygame не могу реализовать коллизию между кнопки мыши и изображением

Рейтинг: 0Ответов: 1Опубликовано: 13.05.2023
import pygame
import random

pygame.init()

WIDTH,HEIGHT = 800,600
SCREEN = pygame.display.set_mode((WIDTH,HEIGHT))
BG = pygame.transform.scale(pygame.image.load('images/bg.jpeg'), (WIDTH , HEIGHT)).convert()
pinky = pygame.transform.scale(pygame.image.load('images/pinky.png'), (60,120))
clock = pygame.time.Clock()
aim = pygame.transform.scale(pygame.image.load('images/aim.png'), (75,75))

class Baloons:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.img = pinky
        self.rects = pinky.get_rect()

    def draw(self, window):
        window.blit(self.img, (self.x, self.y))

    def move(self, speed):
        self.y -= speed


def main():
    run = True
    FPS = 60
    speed = 3
    baloons = []

    def redraw():
        SCREEN.blit(BG, (0,0))
        for baloon in baloons:
            baloon.draw(SCREEN)
        mouse_x, mouse_y = pygame.mouse.get_pos()
        SCREEN.blit(aim,(mouse_x-37 , mouse_y-35))

        pygame.display.flip()

    while run:
        clock.tick(FPS)
        redraw()
        if len(baloons) == 0:
            for i in range(4):
                baloon = Baloons(random.randint(50,WIDTH - 100), random.randint(700,1500))
                baloons.append(baloon)

        mouse = pygame.mouse.get_pos()
        for baloon in baloons:

Именно тут я не смог реализовать коллизию

            if baloon.rects.collidepoint(mouse) and pygame.mouse.get_pressed()[0]:
                print("TEST")
                baloons.remove(baloon)
            baloon.move(speed)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
main()

Ответы

▲ 1Принят

Вы не двигаете rect шара поэтому нужно смещать положение мыши на x и y шара:

if baloon.rects.collidepoint(mouse[0] - baloon.x,
                             mouse[1] - baloon.y) and pygame.mouse.get_pressed()[0]: