-1

I am making code in pygame where an entity will constantly be switching between two sprites (running animation) and to do so, I had this loop inside the while loop that runs the program. However, I had used time.sleep() at the end of the loop so that it has a small amount of time before switching to the other sprite so it doesn't look weird. However, I'm running into issues because when an event occurs after this code, it takes a little to long because it waits for the timer to run out. How do I revise the code so that the following code can run immediately?

  sprites = [pygame.image.load("./images/dinorun1.png"), pygame.image.load("./images/dinorun2.png")]
  sval = 0
  while running:
      rect = pygame.Rect(xpos, ypos, dinow, dinoh)
      if animation:
        if sval >= len(sprites):
            sval = 0
        image = sprites[sval]
        screen.blit(image, rect)
        sval +=1
        time.sleep(.3)
 
amahd
  • 67
  • 4

1 Answers1

0

There are a few things you need to do to enable what want.

(1) Start using pygame.time.Clock to let your app run at a desired framerate, and to allow framerate-independence/delta-time.

(2) Use the the clock to switch your sprite every few frames, instead of time-based intervals.

Optional. (3) Just a suggestion, instead of using an if statement to reset your sprite frame, use the modulo operator (Example below)

Here is a combined example of these things. This is also good practice as it will make it easier to expand your app or game.

# Pygame setup...

clock = pygame.time.Clock()

# Everything else...

sprites = [pygame.image.load("./images/dinorun1.png"),
           pygame.image.load("./images/dinorun2.png")]
sval = 0

sframes = 10 # Frames before switching sprites

while running:
    # Event handling
    rect = pygame.Rect(xpos, ypos, dinow, dinoh)

    sval = sval % len(sprites)

    if animation:
        image = sprites[int(sval)]
        screen.blit(image, rect)

        sval += (1/sframes) # Use decimals to manage delay between frames

    clock.tick(60) # FPS: 60

Hope I could help!

SimplyDev
  • 90
  • 2
  • 11
  • Actually, the clock aspects are what I had initially, but I changed it to my current code because I wanted only that sprite to change at that rate because there were other things going on that needed to be animated faster. Basically, to get it how I want it, I'd have to make the FPS around 10, which is way too slow for the other things going on in the code that I didn't include. I changed it to what I have now in hopes to make it so only that loop would be affected, which didn't work – amahd Apr 26 '23 at 03:21
  • The example above does just that. It switches the sprite without blocking the entire code. It can run at 60 FPS, but the sprite will not switch that fast. If you want other things also to run, simply ignore the sprite-switching code. All systems in your code should be independent (take that with a grain of salt). – SimplyDev Apr 27 '23 at 01:12