0

This first is my first question so if I am not following some sort of rule or something please let me know. Anyway, I was following a tutorial and trying to make it so the sprite/cube can't go off the screen.

When I run the program, its not like there is any errors or anything but the cube can still go off the screen. Any ideas!?

everything below is in the game loop besides the variables, also 500 by 500 is the window size

x = 500
y = 300
width = 50
height = 50
velocity = 0.1

   keys = pygame.key.get_pressed()

if keys[pygame.K_a] or keys[pygame.K_LEFT] and x > velocity: # left arrow key, last part keeps it from moving off screen
    x -= velocity
if keys[pygame.K_d] or keys[pygame.K_RIGHT] and x < 500 - width - velocity:
    x += velocity
if keys[pygame.K_w] or keys[pygame.K_UP] and y < velocity:
    y -= velocity
if keys[pygame.K_s] or keys[pygame.K_DOWN] and y > 500 - height - velocity:
    y += velocity


screen.fill((0,0,0)) # makes the old sqaure black (screen color)
rect = pygame.draw.rect(screen, (255, 0, 0), (x, y, width, height)) # creates a rectangle: surface, color, (x, y, width, height)
pygame.display.update() # important!
CodeWon
  • 13
  • 3

2 Answers2

0

See How can I make a sprite move when key is held down and Window border in pygame.

Use min and max limit the coordinates of the objet:

keys = pygame.key.get_pressed()
x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * velocity
y += (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * velocity

x = max(0, min(500 - width, x))
y = max(0, min(500 - height, y))
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
0

After doing a ton of thinking, i made this by my self:

if keys[pygame.K_a] or keys[pygame.K_LEFT]:
    if x > 0:
        x -= velocity
if keys[pygame.K_d] or keys[pygame.K_RIGHT]:
    if x < 500 - width:
        x += velocity
if keys[pygame.K_w] or keys[pygame.K_UP]:
    if y > 0:
        y -= velocity
if keys[pygame.K_s] or keys[pygame.K_DOWN]:
    if y < 500 - height:
        y += velocity
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
CodeWon
  • 13
  • 3