'How do i keep my player in pygame from going off of the screen
So i've been working lately on some 2D game for my school's final project... And i needed to make my player or the controlled object so it doesn't go off of the screen/window
I've only managed to make the right and the buttom side of the screen
Here is the entire code
Thanks to whoever can help!
import pygame
import os
from pygame import draw
pygame.font.init()
WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)
pygame.display.set_caption("Hello, World!")
FPS = 60
WHITE = pygame.color.Color('#FFFFFF')
x, y = 20, 20
player = pygame.image.load(os.path.join("Assests", "player1.png"))
player = pygame.transform.scale(player, (200, 200))
player_vel = 5
def main():
clock = pygame.time.Clock()
run = True
while run:
clock.tick(FPS)
# redraw_window()
WIN.fill(WHITE)
keys = pygame.key.get_pressed()
global x, y
pressed = pygame.key.get_pressed()
if pressed[pygame.K_w]: y -= 5
if pressed[pygame.K_s] and y < HEIGHT - 140: y += 5
if pressed[pygame.K_a]: x -= 5
if pressed[pygame.K_d] and x < WIDTH - 120: x += 5
WIN.blit(player, (x, y))
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
WIN.blit(player, (x, y))
pygame.quit()
main()
Solution 1:[1]
The answer for this is:
if pressed[pygame.K_w] and y-67 > 0: y -= 5
if pressed[pygame.K_s] and y < HEIGHT - 140: y += 5
if pressed[pygame.K_a]: x - 127 > 0 -= 5 # Try changing the numbers to get it right
if pressed[pygame.K_d] and x < WIDTH - 120: x += 5
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Amine Khiari |