Python Pygame Mask Collision
when I try to use this piece of code, it only works for 1 object, not for every. I'm trying to modify code from this video (https://www.youtube.com/watch?v=Idu8XfwKUao). Is there i
Solution 1:
Your application works fine. The issue is, that result of each evaluation of overlap
cause a change of blob_color
. So the last obstacle in the loop "wins". If the last obstacle overlaps
the blob, then the color is orange_blob
, else it is green_blob
.
Set the green color before the loop. If any obstacle overlaps
the blob, then change it to orange. The blob has to be drawn once after the loop. e.g.:
whileTrue:
events()
blob_color = green_blob
for i inrange(4):
mx, my = pygame.mouse.get_pos()
offset = (int(mx - ox[i]), int(my - oy[i]))
if obstacle_mask[i].overlap(blob_mask, offset):
blob_color = orange_blob
screen.blit(obstacle[i], (ox[i], oy[i]))
screen.blit(blob_color, (mx, my))
To find obstacle at random positions, which are not overlapping, you have to evaluate if a new obstacle hits any of the former obstacles. Create a random position:
x, y = random.randint(100, 400), random.randint(100, 400)
And evaluate if there is any
obstacle that overlap
s the new position.
isect = any(obstacle_mask[j].overlap(obstacle_mask[i], (x-ox[j], y-oy[j])) for j inrange(i))
If that is the case, then repeat the process. Create a new random position and test for overlapping:
obstacle = []
obstacle_mask = []
oy = []
ox = []
for i inrange(4):
obstacle.append(pygame.image.load("obstacle-400x399.png").convert_alpha())
obstacle_mask.append(pygame.mask.from_surface(obstacle[i]))
isect = Truewhile isect:
x, y = random.randint(100, 400), random.randint(100, 400)
isect = any(obstacle_mask[j].overlap(obstacle_mask[i], (x-ox[j], y-oy[j])) for j inrange(i))
ox.append(x)
oy.append(y)
Post a Comment for "Python Pygame Mask Collision"