I have added an Object/Image on the main_screen
, the object is called cancer_cell
.
What I'm trying to do here is that I want the object move smoothly. I have to repeatedle press on the arrow keys to keep it moving.
How do I make it move while
arrow keys are pressed ?
here's the code:
exitgame = False
cellpos_x = 0
cellpos_y = cancer_cell.get_rect().height*2
while not exitgame:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exitgame = True
quitgame()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
cellpos_x -= 10
if event.key == pygame.K_RIGHT:
cellpos_x += 10
gameplay_bg = pygame.image.load("/Users/wolf/Desktop/python/img/gameplay_bg.png").convert()
main_screen.fill(white)
main_screen.blit(gameplay_bg, [0,0])
main_screen.blit(cancer_cell, [cellpos_x, cellpos_y])
pygame.display.flip()
clock.tick(20)
someone told me to try the solution at How to use pygame.KEYDOWN: but that didn't work either. Or maybe i did it wrong:
if event.type == pygame.KEYDOWN:
key_pressed = pygame.key.get_pressed()
if key_pressed[pygame.K_LEFT]:
cellpos_x -= 10
if key_pressed[pygame.K_RIGHT]:
cellpos_x += 10
PROBLEM SOLVED
I have solved the problem by just unindenting this part from the
FOR
loop while not exitgame:I see you've solved the indentation issue, here's another version of your example:
You need to adjust the paths of the images ("background.jpg", "player.jpg"), with this version you're not loading over and over your sprite in the game event loop and the Player movement will be smooth.