I'm still pretty new to pygame, and coding in general. I'm making a game that requires collision detection, and I seem to be having a problem with it. Every time I run my program, it detects non-existent collisions. Here are some snippets from my code:
class Player(pygame.sprite.Sprite):
def __init__(self,x,y,width,height):
pygame.sprite.Sprite.__init__(self)
self.x = x
self.y = y
self.width = width
self.height = height
self.right = False
self.left = False
self.up = False
self.down = False
self.surf = pygame.Surface((50,50))
self.rect = self.surf.get_rect()
def draw(self):
pygame.draw.rect(screen, (0,0,0), (self.x, self.y, self.width, self.height))
def collision_test(self):
if pygame.sprite.collide_rect(self, block1):
print("a collision is detected")
The above is my player class.
class Block1(pygame.sprite.Sprite):
def __init__(self,x,y,width,height):
pygame.sprite.Sprite.__init__(self)
self.x = x
self.y = y
self.width = width
self.height = height
self.surf = pygame.Surface((self.width,self.height))
self.rect = self.surf.get_rect()
def draw(self):
pygame.draw.rect(screen, (150,150,150), (self.x, self.y, self.width, self.height))
And that's my class for the obstacle that my player is supposed to collide with. I'm running a print command in the collision detection for debugging. Like I said, it just constantly prints the message I gave it, even when they aren't colliding. There are no error messages though. Any help would be appreciated! Thanks in advance :)
EDIT:
I changed the collision_test method and added the block1 argument. Now it is this:
def collision_test(self, block1):
if pygame.sprite.collide_rect(self, block1):
print("a collision is detected")
My player and block1 sprites are initiated just before the mainloop, and look like this:
player = Player(50,50,50,50)
block1 = Block1(200, 200, 100, 100)
I am calling the function, collision_test, at the end of the mainloop. In case you need it, here is my full code: https://pastebin.com/LTQdLMuV
collision_test(self)method does not take anyblock1argument. Where thatblock1comes from? Where in the code do you call this function? Please add the portion of code where you instatiate objects from your classes and use them too. - Valentino