I am currently developing a platform game which depends on objects (in the form of platforms) to be their collision in order to prevent the player from exiting the window. Here's my code for collision with platforms/blocks:
#check for collision
self.in_air = True
for tile in world.tile_list:
#collison x
if tile[1].colliderect(self.rect.x + dx,self.rect.y , self.width, self.height):
dx = 0
# collision y
if tile[1].colliderect(self.rect.x, self.rect.y + dy, self.width, self.height):
# below ground?
if self.vel_y < 0:
dy = tile[1].bottom - self.rect.top
self.vel_y = 0
# above ground?
elif self.vel_y >= 0:
dy = tile[1].top - self.rect.bottom
self.vel_y = 0
self.in_air = False
However, this looks unprofessional and I would like to add code which introduces an invisible barrier which stops the player from leaving the screen. I have tried different methods but am currently unsure, any advice would be appreciated.
If you only want to limit the player to a bounding rectangle, I recommend using
pygame.Rect.clamp_ip
Define the bounding respectively border rectangle. If the player is limited to the screen, you can get a rectangle that defines the border from the display Surface with
pygame.display.get_surface()
andpygame.Surface.get_rect
:Clamp the player
pygame.Rect
byborder_rect
:You can do this with 1 line of code:
Minimal example