'pygame - mask collision not working, return always same collision point
I'm trying to create a pixel-perfect collision but if I try to print the collision value I always get collision on point (8, 0). this is my code, thank you.
collisionsroom1 = pygame.image.load("images/collisionsroom1.png")
characterhitbox = pygame.image.load("images/characterhitbox.png")
def collision():
mouseposx, mouseposy = pygame.mouse.get_pos()
ROOTwidth, ROOTheight = pygame.display.get_surface().get_size()
#room 1 collision
collisionsroom1 = pygame.transform.scale(collisionsroom1, (ROOTwidth/2.3, ROOTheight))
ROOT.blit(collisionsroom1, [ROOTwidth/2-room1_width/2,0])
collisionsroom1_mask = pygame.mask.from_surface(collisionsroom1)
#character hitbox
characterhitbox = pygame.transform.scale(characterhitbox, (ROOTheight/30, ROOTheight/30))
characterhitbox_width = characterhitbox.get_width()
characterhitbox_height = characterhitbox.get_height()
ROOT.blit(characterhitbox, [mouseposx-characterhitbox_width/2, mouseposy-
characterhitbox_height/2])
while True:
mouseposx, mouseposy = pygame.mouse.get_pos()
#get character updated mask position
ROOT.blit(characterhitbox, [mouseposx-characterhitbox_width/2, mouseposy-
characterhitbox_height/2])
characterhitbox_mask = pygame.mask.from_surface(characterhitbox)
#room collisions
offset = 0, 0
collision = characterhitbox_mask.overlap(collisionsroom1_mask, offset)
print (collision)
if collision:
print("yescollision")
else:
print("nocollision")
Solution 1:[1]
See PyGame collision with masks. Your code can't work, because of offset = 0, 0. The offset must be the distance between the top left corners of the images:
offset = (character_x - room_x), (charcater_y - room_y)
collision = characterhitbox_mask.overlap(collisionsroom1_mask, offset)
In the example above, (room_x, room_y) is the position of the room and (character_x, character_y) is the position of the character.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rabbid76 |
