for i in objects:
if self.y self.y_vel > HEIGHT self.ySize:
self.y_vel = 0
break
elif pygame.Rect.colliderect(self.rect, i.rect):
self.y_vel = 0
break
else:
self.y_vel = 0.05
this code works all right till the last else because the for loop maybe hasn't reached the object its colliding with so it gives it gravity so my question is is there a way to do pygame.Rect.colliderect(self.rect, all(i).rect)
but that doesn't work I experimented with all() but I don't really know how that would work any help is appreciated
CodePudding user response:
You don't want to use all
but any
. Also, you need to restructure the code, because when the object collides with the ground, you don't need to check for collisions with objects:
if self.y self.y_vel > HEIGHT self.ySize:
self.y_vel = 0
else:
if any(self.rect.colliderect(o.rect) for o in objects):
self.y_vel = 0
else:
self.y_vel = 0.05
However, you don't want to let the object float slightly over the obstacle. So you might want to place the object tight to the obstacle when you detect a collision:
self.rect.y = self.y self.y_vel
if self.rect.bottom > HEIGHT:
self.rect.bottom = HEIGHT
self.y = self.rect.y
self.y_vel = 0
else:
collided = False
for o in objects:
if self.rect.colliderect(o.rect):
collided = True
self.rect.bottom = o.rect.top
self.y = self.rect.y
self.y_vel = 0
break
if not collided:
self.y_vel = 0.05