简体   繁体   中英

pygame sprite not moving across screen when updates

I am trying to move my sprite across the screen when the window starts.... It moves for a second than stops for a while than it starts back up again. its not giving me an error.... So im really not sure whats going on here.... anyway here is the code.... any info is needed!

thanks,

import pygame
from sys import exit
pygame.init()
screen = pygame.display.set_mode((800,400))


sky_surface = pygame.image.load("bg_desert.png")
snail_surface = pygame.image.load("snailWalk1.png")
snail_x_pos = 600

while True:
    

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
        snail_x_pos -=1
        screen.blit(sky_surface,(0,0))
        
        screen.blit(snail_surface,(snail_x_pos,350))
      
        pygame.display.update()
       
       
        


Your loop will only execute when there are events. When there are no events, you don't move. If you wiggle your mouse in front of the screen, for example, you'll see pretty continuous movement.

You need to use pygame.time.set_timer to force an event for you to update.

It looks like the final 4 lines you have written are designed to run on each cycle of the for loop, however they will only run when an event occurs, because they are indented a block too far.

Your new code should look like this:

import pygame
from sys import exit
pygame.init()
screen = pygame.display.set_mode((800,400))


sky_surface = pygame.image.load("bg_desert.png")
snail_surface = pygame.image.load("snailWalk1.png")
snail_x_pos = 600

while True:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

    snail_x_pos -=1
    screen.blit(sky_surface,(0,0))
    screen.blit(snail_surface,(snail_x_pos,350))
    pygame.display.update()

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