how to teleport player to the other side of the screen when he touches the screen border?

Question:

I am new to pygame (and coding) and can’t figure out how to move my player from one side of the screen to the other, like the side gates in pacman, here’s my code i hope someone can help me cuz it’s seems like it’s something easy but i just can’t think of a solution yet

import pygame

white=(255,255,255)
yellow=(255,255,102)
black=(0,0,0)
red=(213,50,80)
green=(0,255,0)
blue=(50,153,213)

dis_witdh,dis_height=1920,1080
dis=pygame.display.set_mode((dis_witdh,dis_height))

pygame.display.set_caption("")

fps=60
velocity=6
border=pygame.Rect((0,0), (dis_witdh, dis_height))
player_witdh=10
player_height=10

def draw_widow(player):
    dis.fill(black)
    pygame.draw.rect(dis, white, [player.x ,player.y ,player_witdh,player_height])
    pygame.display.update()

def movement(keys_pressed,player):
    if keys_pressed[pygame.K_a] and player.x-velocity>-1:
        player.x-=velocity
    if keys_pressed[pygame.K_d] and player.x+velocity<dis_witdh-9:
        player.x+=velocity
    if keys_pressed[pygame.K_w] and player.y+velocity>9:
        player.y-=velocity
    if keys_pressed[pygame.K_s] and player.y+velocity<dis_height-9:
        player.y+=velocity
    if keys_pressed[pygame.K_ESCAPE]:
        pygame.quit()

def world_generation():


def main():
    player=pygame.Rect(dis_witdh/2,dis_height/2,player_witdh,player_height)
    clock=pygame.time.Clock()
    run=True
    while run:
        clock.tick(fps)
        for event in pygame.event.get():
            if event.type==pygame.QUIT:
                run=False

        keys_pressed=pygame.key.get_pressed()

        movement(keys_pressed,player)
        draw_widow(player)

    pygame.quit()

if __name__=="__main__":
    main()
Asked By: tesco

||

Answers:

When a player tries to move left, check if their new x-position puts them off the left edge of the screen. If it is, update their x-position to put them on the right side of the screen. Try updating your movement function like this:

def movement(keys_pressed,player):
    if keys_pressed[pygame.K_a]:
        new_x = player.x - velocity
        if new_x < 0
            new_x = dis_width + new_x
        player.x = new_x
    # Add other directions here
Answered By: jprebys

Use the % (modulo) operator and calculate the remainder of the division of the player position and the size of the screen:

def movement(keys_pressed,player):
    player.x += (keys_pressed[pygame.K_d] - keys_pressed[pygame.K_a]) * velocity
    player.y += (keys_pressed[pygame.K_s] - keys_pressed[pygame.K_w]) * velocity
    player.x = player.x % dis_witdh
    player.y = player.y % dis_height

Note:

>>> width = 100
>>> 101 % width
1
>>> -1 % width
99
>>>
Answered By: Rabbid76
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.