AmanoSkullGZ
AmanoSkullGZ

Reputation: 141

The player character isn't moving

So, I'm having some trouble developing the space ship movement on my game. I checked the code a couple of times and yet I still can't find nothing. The project is from this video https://www.youtube.com/watch?v=FfWpgLFMI7w and I got this bug on the minute 44:55, and I'm using Python 3.8. Here's the code.

import pygame

# Initiate pygame
pygame.init()

# Display the game window
screen = pygame.display.set_mode((800,600))

# Title and Icon
pygame.display.set_caption('Space Invaders')
icon = pygame.image.load('icon.png')
pygame.display.set_icon(icon)

# Player
playerSprite = pygame.image.load('player.png')
playerX = 370
playerY = 480
playerX_change = 0

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

# Game Loop
running = True
while running:

    # Background color (RGB)
    screen.fill((0, 0, 0))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        # If a key is pressed, check if it's the right or left arrow key
        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

    # Move the spaceship to the left or right
    playerX_change += playerX
    player(playerX,playerY)
    pygame.display.update()

Upvotes: 1

Views: 45

Answers (1)

Rabbid76
Rabbid76

Reputation: 210909

You have to change the position of the player (playerX) rather than the movement distance playerX_change:

playerX_change += playerX

playerX += playerX_change 

Anyway, the code can be simplified by the use of pygame.key.get_pressed(). pygame.key.get_pressed() returns a sequence of boolean values representing the state of every key:

# Game Loop
running = True
while running:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Move the spaceship to the left or right
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        playerX -= 0.1
    if keys[pygame.K_RIGHT]:
        playerX += 0.1

    # Background color (RGB)
    screen.fill((0, 0, 0))

    player(playerX,playerY)
    pygame.display.update()

Upvotes: 1

Related Questions