-1

I was making a game in pygame and i needed to detect collision between the player and the enemy while making the function to check this i ran it and it always returns "False" here is my code: def collision(): if Game.player.colliderect(Game.enemy): print(True) else: print(False)

when called in an update function thats in the main game loop it should detect collision, but it doesn't.

1 Answers1

0

You aren’t applying the correct logic for collision. How would the program know if you have collided with the enemy. It can be done in many ways, one of the way is checking whether their positions are same or not, either vertical or horizontal.

# collision detection
def crash():
  # take a global variable
  global blockYPosition
  
  # check conditions
  if playerYPosition < (blockYPosition + pixel):
  
      if ((playerXPosition > blockXPosition 
           and playerXPosition < (blockXPosition + pixel))
          or ((playerXPosition + pixel) > blockXPosition
           and (playerXPosition + pixel) < (blockXPosition + pixel))):
  
          blockYPosition = height + 1000

The above code, I have taken an example of a cube colliding with another. You can modify the code as you need.

Thanks,

Hardyk Mahendru
  • 320
  • 3
  • 11