Search code examples
pythonpygamepngcollisiondetection

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()" then "rect.colliderect(another rect of other image)} and this way both.

I used cat.png in two sprites.

Questions

Is cat.png bad?

Am I not using the right scripts?

Is my computer weird?

Here are my scripts and the cat.png.

enter image description here

import pygame, sys, time
from pygame.locals import *

pygame.init()

Fps = 100
fpsClock = pygame.time.Clock()

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

white = (255, 255, 255)

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

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

     def colde(self, sprite1, sprite2):
          col = pygame.sprite.collide_rect(sprite1, sprite2)
          if col == True:
               print("crash!")

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

while True:
    Displaysurf.fill(white)
    cat1.draw()
    cat2.draw()

    for event in pygame.event.get():
        if event.type==QUIT:
            pygame.quit()
            sys.exit()

    keys = pygame.key.get_pressed()
    if keys[pygame.K_UP]:
        cat1.y -= 3
    if keys[pygame.K_DOWN]:
        cat1.y += 3
    if keys[pygame.K_LEFT]:
        cat1.x -= 3
    if keys[pygame.K_RIGHT]:
        cat1.x += 3
    cat1.colde(cat1, cat2)
    pygame.display.update()
    fpsClock.tick(Fps)`

Solution

  • 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)
    
    class Cat:
    
        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
    
        def draw(self, surface):
            surface.blit(self.img, self.rect)
    
        def colide(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 = True
    
    while 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 -= 3
        if keys[pygame.K_DOWN]:
            cat1.rect.y += 3
        if keys[pygame.K_LEFT]:
            cat1.rect.x -= 3
        if 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()