1

I call check_collision() on line 42 in my game loop. The purpose of this is to check if the two rects (the two players in the game) have collided or not. What I am unclear about is what arguments I should use. I don't think using the XY coordinates of the two rects would work, and I don't know of any way to assign the rects to variables that could be used as arguments. Any help would be appreciated.

Code:

import pygame, sys

pygame.init()

win = pygame.display.set_mode((500, 500))

clock = pygame.time.Clock()

class Player():
  def __init__(self, x, y, width, height, speed):
    self.x = x
    self.y = y
    self.width = width
    self.height = height
    self.speed = speed
  
  def movement_up(self):
    pass
    #more boilerplate movement code

  def check_collision(player1, player2):
    check = pygame.sprite.collide_rect(player1, player2)
    if check == True:
      sys.exit()

enemy = Player(30, 30, 60, 60, 5)
person = Player(0, 0, 60, 60, 5)

game_loop = True
while game_loop == True:
  clock.tick(60)
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      game_loop = False

  keys = pygame.key.get_pressed()

  if keys[pygame.K_a]:
    #boilerplate movement code
    pass

  person.check_collision()  # <-- what to put here

  win.fill((0, 0, 0))
  pygame.draw.rect(win, (255, 0, 0), (person.x, person.y, person.width, person.height))
  pygame.draw.rect(win, (0, 0, 255), (enemy.x, enemy.y, enemy.width, enemy.height))
  pygame.display.update()

pygame.quit()
the popo
  • 49
  • 3

1 Answers1

1

You can call it like person.check_collision(enemy). However it won't work at all.


You cannot use pygame.sprite.collide_rect, because player1 and player2 are not pygame.sprite.Sprite objects. However, you can create pygame.Rect objects and use colliderect:

class Player():
    # [...]

    def check_collision(self, enmey):
        self_rect = pygame.Rect(self.x, self.y, self.width, self.height)
        enmey_rect = pygame.Rect(enmey.x, enmey.y, enmey.width, enmey.height)
        if self_rect.cooliderect(enmey_rect):
            sys.exit()
enemy = Player(30, 30, 60, 60, 5)
person = Player(0, 0, 60, 60, 5)

game_loop = True
while game_loop == True:
    # [...]

    person.check_collision(enemy)

See also How do I detect collision in pygame?


You can greatly simplify your code by removing the attributes x, y, width and height, but add an attribute rect:

class Player():
    def __init__(self, x, y, width, height, speed):
        self.rect = pygame.Rect(x, y, width, height)
        self.speed = speed
  
    def movement_up(self):
        pass
        #more boilerplate movement code

    def check_collision(self, enmey):
        if self.rect.colliderect(enmey.rect):
            sys.exit()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174