Alex D'ago
Alex D'ago

Reputation: 162

how to make an object appear at the beginning(or end) once off the borders of the window (with pygame)

So I am trying to work a little bit with simple animations and collisions in pygame.I’m trying to make a rectangle appear at the beginning(or end) once it gets off the border, but even if my approach works when dealing with the y coordinate, it miserably fails with the x-axis.However I cannot quite get why.

This is the piece of code that probably causes trouble

def movement():
    keys_pressed = pygame.key.get_pressed()
    if keys_pressed[pygame.K_a]:
        red_rect.x -= vel
    if keys_pressed[pygame.K_d]:
        red_rect.x += vel
    if keys_pressed[pygame.K_w]:
        red_rect.y -= vel
    if keys_pressed[pygame.K_s]:
        red_rect.y += vel
    if (red_rect.x) == 600:
        red_rect.x = 0
    if red_rect.x == 0:
        red_rect.x = 600
    if red_rect.y == 600:
        red_rect.y = 0
    if red_rect.y == -40:
        red_rect.y = 600

Could also someone tell me ho to make appear on the other side the portion off the other border(the rectangle shouldn't change immediately position so that the transition is smoother) Thank you for any tip or answer

Upvotes: 2

Views: 53

Answers (1)

Rabbid76
Rabbid76

Reputation: 210909

Do not check whether the coordinates are equal to (==) 0 or 600, but rather check whether the coordinates are < 0 or >= 600:

if (red_rect.x) >= 600:
    red_rect.x = 0
if red_rect.x < 0:
    red_rect.x = 600
if red_rect.y >= 600:
    red_rect.y = 0
if red_rect.y < 0:
    red_rect.y = 600

Your code can be greatly simplified. pygame.key.get_pressed() returns an array with 0s and 1s. Use the values to calculate the movement. Use the modulo (%) operator to calculate the position:

def movement():
    
    keys_pressed = pygame.key.get_pressed()
    red_rect.x += (keys_pressed[pygame.K_d] - keys_pressed[pygame.K_a]) * vel
    red_rect.y += (keys_pressed[pygame.K_s] - keys_pressed[pygame.K_w]) * vel
    
    width, height = 600, 600
    red_rect.x = red_rect.x % width
    red_rect.y = red_rect.y % height

Upvotes: 2

Related Questions