简体   繁体   中英

Pygame simple issue, object movement and display

    player_1 = pygame.image.load(player1)
    #

    def player1(x,y):
        window.blit(player_1, (x,y))

    x =  (110)
    y = (150)
    x_change = 0
    y_change = 0
    player1_speed = 0

    while not gameover:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
               gameover = True

            if event.type == pygame.KEYDOWN:
               if event.key == pygame.K_LEFT:
                x_change = -5
               elif event.key == pygame.K_RIGHT:
                  x_change = 5

               elif event.key == pygame.K_UP:
                  y_change = -5

              elif event.key == pygame.K_DOWN:
                 y_change = 5

        if event.type == pygame.KEYUP:
        if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_UP or event.key == pygame.K_DOWN:
            x_change = 0


        x += x_change
        y += y_change        

        player1(x,y)
        pygame.display.update()
        fpsClock.tick(60)
        screen.blit(background_surface, (0,0))

# update display
pygame.display.flip()

Hi, I have a program where unfortunatley when moving the object, it moves left & right perfectly but up and down does not seem to stop. There is also an issue of the screen flashing. Sorry for the long question but any help would be appreciated. Thanks

1. As far as I see you are only blitting player1. Where is player2?

2. You are missing some indentation in your code. I guess the correct form would be:

 if event.type == pygame.KEYUP:
    if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_UP or event.key == pygame.K_DOWN:
        x_change = 0

3. Then your are only setting x_change to 0. I guess you want to set y_change to 0 as well... even though you have to make your query more specific by grouping up vertical and horizontal keys.

Like:

if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
    x_change = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
    y_change = 0

4. You call the blit method after updating the screen. Moving pygame.display.update() after screen.blit(..) would fix some things...

5. The flip method is outside of your loop. It will only be called if your game loop breaks!

Little hint: Copy-Pasting is a very bad practice. Try to do it yourself instead!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM