I tried using something like this but it did not work.
while running:
keys = pygame.key.get_pressed() #checking pressed keys
if keys[pygame.K_UP]:
y1 -= 1
if keys[pygame.K_DOWN]:
y1 += 1
Here is the code I have at the moment. I tried using a different method because the above method did not work for me. It moves it one button tap at a time.
import pygame
spaceX = 100
spaceY = 100
pygame.init
black = (0,0,0)
size = (800, 800)
screen = pygame.display.set_mode(size)
def game(spaceX, spaceY):
spaceship_file = 'spaceship.png'
spaceship_image = pygame.image.load(spaceship_file)
spaceship = pygame.transform.scale(spaceship_image, (30, 30))
screen.fill(black)
screen.blit(spaceship, (spaceX, spaceY))
pygame.display.flip()
while True:
for event2 in pygame.event.get():
if event2.type == pygame.KEYDOWN and event2.key == pygame.K_LEFT:
spaceX2 = spaceX - 5
game(spaceX2, spaceY)
elif event2.type == pygame.KEYDOWN and event2.key == pygame.K_RIGHT:
spaceX2 = spaceX + 5
game(spaceX2, spaceY)
game(spaceX, spaceY)
EDIT:
I have this code now. My object still only moves when I repeatedly tap the button and not when I hold it down.
def game(spaceX, spaceY):
while True:
screen.fill(black)
screen.blit(spaceship, (spaceX, spaceY))
pygame.display.flip()
keys = pygame.key.get_pressed()
for event in pygame.event.get():
if keys[pygame.K_LEFT]:
spaceX = spaceX - 5
game(spaceX, spaceY)
elif keys[pygame.K_RIGHT]:
spaceX = spaceX + 5
game(spaceX, spaceY)