Ved Pawar
Ved Pawar

Reputation: 148

My space ship won't move towards right in pygame

import pygame
#initialize the screen
pygame.init()

#create the screen
screen = pygame.display.set_mode((800, 700))

#tile and icon
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load("spaceship.png")
pygame.display.set_icon(icon)

#Player
playerImg = pygame.image.load("player.png")
playerx = 370
playery = 600
playerx_change = 0.1

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

running = True
while running:

    screen.fill((0,0,0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        #keystroke
        if event.type == pygame.KEYDOWN:
           if event.key == pygame.K_LEFT:
                playerx_change = -0.1
           if event.type == 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
            

    playerx += playerx_change
    player(playerx,playery)
    pygame.display.update()  

my spaceship won't move towards right side when i press the riht key. but it will move towards the left side if i press the left key and no error is displayed in the terminal. i use the community version of visual studio 2019.

Upvotes: 1

Views: 58

Answers (1)

Nikolaj Kiel
Nikolaj Kiel

Reputation: 86

You need to change this:

if event.type == pygame.K_RIGHT:

to this ("type" --> "key"):

if event.key == pygame.K_RIGHT:

Upvotes: 1

Related Questions