Skip to content Skip to sidebar Skip to footer

Python Collision Detection Of Image With Pygame (image Type : Png)

I want to make the Collision Detection scripts. When I run my scripts Pygame always say the images are in collision. It prints 'crash' when I use {'rect = cat1.img.get_rect()' the

Solution 1:

You have to use cat1.rect.x and cat1.rect.x instead of cat1.x and cat1.y to move object and then use cat1.rect to check collision and to draw it

self.rect.colliderect(other_sprite)

surface.blit(self.img, self.rect)

Code:

import pygame

# --- constants --- (UPPER_CASE_NAMES)

FPS = 100
WHITE = (255, 255, 255)

# --- classes --- (CamelCaseNames)classCat:

    def__init__(self, x, y):
        self.img = pygame.image.load('cat.png')
        self.rect = self.img.get_rect()
        self.rect.x = x
        self.rect.y = y

    defdraw(self, surface):
        surface.blit(self.img, self.rect)

    defcolide(self, other_sprite):
        col = self.rect.colliderect(other_sprite)
        if col:
            print("crash!")

# --- main --- (lower_case_names)# - init -

pygame.init()

display_surf = pygame.display.set_mode((300, 300)) # full is 1900, 1000
pygame.display.set_caption('Animation')

# - objects -

cat1 = Cat(10, 10)
cat2 = Cat(100, 100)

# - mainloop -

fps_clock = pygame.time.Clock()
running = Truewhile running:

    # - events -for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    keys = pygame.key.get_pressed()

    if keys[pygame.K_UP]:
        cat1.rect.y -= 3if keys[pygame.K_DOWN]:
        cat1.rect.y += 3if keys[pygame.K_LEFT]:
        cat1.rect.x -= 3if keys[pygame.K_RIGHT]:
        cat1.rect.x += 3# - updates (without draws) -

    cat1.colide(cat2)

    # - draws (without updates) -

    display_surf.fill(WHITE)
    cat1.draw(display_surf)
    cat2.draw(display_surf)

    pygame.display.update()

    fps_clock.tick(FPS)

# - end -

pygame.quit()

Post a Comment for "Python Collision Detection Of Image With Pygame (image Type : Png)"