如何在 pygame 中保持 60 fps 的同时减慢精灵动画的速度?

How to slow down sprite animation while maintaining 60 fps in pygame?

我正在尝试创建一款平台游戏,我想在其中保持 60 FPS,而不会让 sprite 动画移动得非常快。我已经看到关于如何使用时间模块这样做的其他答案,但我真的不明白如何应用它。

主要代码:

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

如果有人想复制我的情况,这里是 spritesheet:

我 100% 相信有更好的方法,但我会创建一个名为 animation_tick 的新变量,并在 while 循环中的每次迭代中为其添加一个变量。仅每 n ticks 调用精灵更改以增加更改之间的延迟。

只有必要部分的示例代码:

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

它实际上只是一个 while 循环中的 for 循环