I am currently making my first game with pygame, where I use classes. My goal is to make the player move according to the input given, but somehow I can't get it to work, I have used different approaches but my best ones looked this this:
The player does move to the left when I click a
, but if I release a
it keeps moving, pressing d
doesn't seem to work at all, even though I tested both inputs with print("a/d is pressed")
and they worked as intended.
Here's the code I currently have in the class:
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load('img/spaceship.png').convert_alpha()
self.rect = self.image.get_rect(center=(300, 650))
self.a = False
self.d = False
def player_movement_check(self, inputs):
self.inputs = inputs
if self.inputs[pygame.K_a]:
self.a = True
else:
self.a = False
if self.inputs[pygame.K_d]:
self.d = True
else:
self.d = False
def player_movement(self):
if self.a == True:
self.rect.x += -0.2
print("a pressed")
if self.d == True:
self.rect.x += 0.2
print("d pressed")
def update(self, inputs):
self.player_movement_check(inputs)
self.player_movement()
and the later on in the code in the while loop:
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.blit(background, (0, 0))
inputs = pygame.key.get_pressed()
player.draw(screen)
player.update(inputs)
What would be the best way to make the player move, but stop moving whenever nothing is pressed. I would also like if the player would change directions according to the last input, for example, if I first press and hold a
, but then press d
, that it starts moving to the right even though a
is pressed, and when I let go of d
it moves to the left again (This would smoothen the movement a lot in my opinion, as you wouldn't have to let go of a
before pressing d
or else the player just stops when you let go of a
even though d
is still pressed).