1

For my alevel coursework I am making a game using pygame. I have come into a problem where on the left side and the top prevent my sprite passing the boarder but for the right side and bottom when I go past that barrier the sprite appears on the opposite edge. I hope that makes sense. Here is the code that I currently have for this section. x1 and y1 are for my first sprite's coordinates and x2 and y2 are for my second.

        if x1 > WIDTH - Char1WIDTH or x1 < 0:
            x1 = 0

        if y1 > HEIGHT - Char1HEIGHT or y1 <0:
            y1 = 0
            
        if x2 > WIDTH - Char2WIDTH or x2 < 0:
            x2 = 0

        if y2 > HEIGHT - Char2HEIGHT or y2 <0:
            y2 = 0
GT02
  • 41
  • 5

1 Answers1

0

If the sprite is on the right, you'll need to align the sprite with the right edge of the window. If the sprite is at the bottom, you'll need to align it at the bottom:

if x1 < 0:
    x1 = 0
if x1 > WIDTH - Char1WIDTH:
    x1 = WIDTH - Char1WIDTH

if y1 < 0:
    y1 = 0
if y1 > HEIGHT - Char1HEIGHT:
    y1 = HEIGHT - Char1HEIGHT

if x2 < 0:
    x2 = 0
if x2 > WIDTH - Char2WIDTH:
    x2 = WIDTH - Char2WIDTH

if y2 < 0:
    y2 = 0
if y2 > HEIGHT - Char2HEIGHT:
    y2 = HEIGHT - Char2HEIGHT

respectively

x1 = max(0, min(WIDTH - Char1WIDTH, x1))
y1 = max(0, min(HEIGHT- Char1HEIGHT, y1))

x2 = max(0, min(WIDTH - Char2WIDTH, x2))
y2 = max(0, min(HEIGHT- Char2HEIGHT, y2))

However I recommend to use pygame.Rect objects and clamp_ip. See pygame.Rect.clamp() respectively pygame.Rect.clamp_ip():

Returns a new rectangle that is moved to be completely inside the argument Rect.

border_rect = pygame.Rect(0, 0, WIDTH, HEIGHT)
player1_rect = pygame.Rect(x1, y1, Char1WIDTH, Char1HEIGHT)
player2_rect = pygame.Rect(x2, y2, Char2WIDTH, Char2HEIGHT)

player1_rect.clamp_ip(border_rect)
x1, y1 = player1_rect.topleft  

player2_rect.clamp_ip(border_rect)
x2, y2 = player2_rect.topleft  
Rabbid76
  • 177,135
  • 25
  • 101
  • 146