How to keep Sonic inside the screen? , n exiting from the sides

Asked

Viewed 47 times

0

import pygame as pg

pg.init()

display_width = 1000

display_height = 600

color_black =(0,0,0)

color_white = (255,255,255)

color_red = (255,0,0)
#tamanho da imagem
sonic_width = 71

window = pg.display.set_mode((display_width,display_height))

pg.display.set_caption('PyRun')

clock = pg.time.Clock()

sonic_img = pg.image.load('sonic1.1.right.png')

moves the Sonic

def sonic(x,y):

    window.blit(sonic_img,(x,y))

def game_loop():

    x = (display_width * 0.15)
    y = (display_height * 0.75)

    x_change = 0

    gameExit = False

    while not gameExit:

        for event in pg.event.get():
            if event.type == pg.QUIT:
                gameExit = True
            if event.type == pg.KEYDOWN:
                if event.key == pg.K_LEFT:
                    x_change = -5
                if event.key == pg.K_RIGHT:
                    x_change = 5

            if event.type == pg.KEYUP:
                if event.key == pg.K_LEFT or event.key == pg.K_RIGHT:
                    x_change = 0

        x += x_change
        window.fill(color_white)
        sonic(x,y)




        pg.display.update()
        clock.tick(60)
game_loop()
pg.quit()
quit()

1 answer

1

You’ll take the width of the screen (width), store it in a variable, and then use the IF to compare whether the character exceeded the width (width) value. If you pass, you cause the character to receive a new location corresponding to the end of your screen. Example with your code:

 if x > display_width:
    window.blit(sonic_img,(display_width,y)) #Manter o personagem sempre antes da margem

 if x < 0:
    x = 0 #Manter o personagem sempre Depois da margem

This way, it can never leave the edges of the screen.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.