Home > Software design >  How to slow down sprite animation while maintaining 60 fps in pygame?
How to slow down sprite animation while maintaining 60 fps in pygame?

Time:02-08

I'm trying to create a platformer game, and I want to maintain 60 FPS in it without having the sprite animations move really quickly. I've seen other answers on how to do so using the time module, but I don't really understand how to apply that.

Main Code:

import pygame
import os
import sys
import random
from pygame.locals import *
import spritesheet
import time

pygame.init()

clock = pygame.time.Clock()
FPS = 60
prev_time = time.time()

pygame.display.set_caption('Platformer')

BG_COLOR = (50, 50, 50)
BLACK = (0, 0, 0)

WIN_SIZE = (1920,1080)

WIN = pygame.display.set_mode(WIN_SIZE, 0, 32)

# CONFIGURING Animations

sprite_sheet_img_IDLE = pygame.image.load('Spritesheets/Outline/120x80_PNGSheets/_Idle.png')
sprite_sheet = spritesheet.SpriteSheet(sprite_sheet_img_IDLE)

IDLE_FRAMES = []
IDLE_STEPS = 9
IDLE_INDEX = 0
INDEX = 0
IDLE_ANIM_SPEED = 20

for x in range(IDLE_STEPS):
    newFRAME = sprite_sheet.get_image(x, 120, 80, 3.5, BLACK)
    IDLE_FRAMES.append(newFRAME)

while True:
    clock.tick(FPS)
    now = time.time()
    dt = now - prev_time
    prev_time = now
    WIN.fill(BG_COLOR)
    WIN.blit(IDLE_FRAMES[], (0, 0))

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

    pygame.display.update()
    if IDLE_INDEX < 8:
        IDLE_INDEX  = 1
    else:
        IDLE_INDEX = 0
    INDEX  = 1

Spritesheet Class:

import pygame

class SpriteSheet():
    def __init__(self, image):
        self.sheet = image

    def get_image(self, frame, width, height, scale, colour):
        image = pygame.Surface((width, height)).convert_alpha()
        image.blit(self.sheet, (0, 0), ((frame * width), 0, width, height))
        image = pygame.transform.scale(image, (width * scale, height * scale))
        image.set_colorkey(colour)

        return image

Here is the spritesheet if anyone wants to replicate my situation:

spritesheet

CodePudding user response:

I'm 100% confident there is a better way to do it, but I would create a new variable called animation_tick and add one to it each iteration in the while loop. Only call the sprite change every n ticks to add delay between changes.

Example code with only necessary parts:

while True:
    if animation_tick == 20: #change 20 to how ever many ticks in between animation frames
        if IDLE_INDEX < 8:
            IDLE_INDEX  = 1
        else:
            IDLE_INDEX = 0
        animation_tick = 0 #reset tick back to 0 after changing frame
    animation_tick  = 1 #add 1 each iteration of the while loop

It's practically just a for loop inside a while loop

  •  Tags:  
  • Related