-1

Here i have written the code for playerX_change (it is the value which was first defined as 0)and when any key was pressed like left or right it should respond by changing the value of x , but it is not

I tried to correct the indexing and also tried to create new variables for it , pls try something else and suggest the recommended changes

here is the code

import pygame

pygame.init()
screen = pygame.display.set_mode((800, 600))

pygame.display.set_caption("It's a game -_-")
icon = pygame.image.load('ufo.png')
pygame.display.set_icon(icon)

running: bool = True

playerimg = pygame.image.load('spaceship3.png')
playerX = 370
playerY = 480


def player(x, y):
    screen.blit(playerimg, (x, y))


while running:
    screen.fill((22, 11, 222))
    playerX_change = 0
    player(playerX, playerY)
    pygame.display.update()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    # it shows basically that every key pressed inside the window gets stored in pygame.event
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            playerX_change = -0.1
        if event.key == pygame.K_RIGHT:
            playerX_change =0.1
    if event.type == pygame.KEYUP:
        if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
            playerX_change = 0

1 Answers1

1

welcome to the community, what you are trying to do is to move the player to the left or right whenever you press the left/right, however, you are not changing the PlayerX variable by the PlayerX_change. This therefore will not move the player, try replacing PlayerX_change = 0 to PlayerX += PlayerX_change so that you update the players X position and that it will only stop on the key up.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174