python - Pygame图像运动异常

标签 python pygame

我正在使用 Pygame 开发一个简单的爱好项目。我有一个图像想要“滑出”到屏幕上。它不会以可靠的速度“滑出”。

图像和窗口的分辨率为 1024x768。我将其从右向左水平滑出。使用 pygame API,我将渲染速度设置为 40 FPS。我想控制它滑到屏幕上的速度(1秒、2秒等),所以我想出了这个小公式来控制图像每帧滑动的速度:

slide_pixels = image_width / (frames_per_sec * slide_time_in_secs)

因此,对于一秒内滑出的 1024 宽图像,图像应以每帧大约 25 像素的速度滑出 (1024/(40 x 1))。准确地说是 25.6 像素,但这并不需要那么精确。问题是图像滑出的速度比应有的速度快得多。对于最简单的情况,一秒钟,似乎是正确的。但对于两个、五个、十个等,它滑出的速度要快得多。我已经打印出增量 (slide_pixels),每次它们看起来都是正确的,因此它应该以正确的速度滑动,并且屏幕似乎以正确的速率刷新(每秒 40 帧)。

下面是相关代码:

#!/usr/bin/env python3

import os
import pygame
import sys


class MyMain:

    def __init__(self):
        pygame.init()
        pygame.mixer.init()
        pygame.display.set_caption("My Project")

        # set FPS
        self.__clock = pygame.time.Clock()
        self.__clock.tick(40)

        self.__screen = pygame.display.set_mode([1024, 768], pygame.DOUBLEBUF, 32)
        self.__mousePosition = pygame.mouse.get_pos()

        # Load resources
        title_path = os.path.join("..", "Assets", "Images", "TitleScreen.png")
        self.__titleImage = pygame.image.load(title_path)

        pygame.mouse.set_visible(True)

    def start(self):
        self.event_handler()

    def event_handler(self):

        # setup for loop
        title_x, title_y = 1024, 0
        self.__screen.fill((0, 0, 0))

        #
        # This is where the problem is?
        #
        slide_in_time = 10 # in seconds
        slide_pixels = title_x / (40 * slide_in_time)

        # Render loop
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()

            # animate and draw image
            if title_x >= 0:
                title_x -= slide_pixels
                if title_x < 0:
                    title_x = 0
            self.__screen.blit(self.__titleImage, (title_x, title_y))

            pygame.display.update()


if __name__ == '__main__':
    MyMain().start()

我是 Python 和 Pygame 的新手。我是否遗漏了一些明显的东西?

最佳答案

您必须每帧调用 self.__clock.tick(40),否则游戏将以您的 CPU 可以达到的最大帧速率运行。

关于python - Pygame图像运动异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49454158/

相关文章:

python - FTP登录获取文件,没有获取到该文件或目录

python - 如何从 shell 一个接一个地运行多个 python 脚本

python - 玩家在预定路径上行走pygame

python - IronPython 中的 LINQ

python - 如何创建一个 RegExp 以匹配最后的 3 个唯一字符和 2 个可选字符?

python - 'kazoo.exceptions.ConnectionLoss' 可能出现多少次?

python - 软件设计与开发专业 : Pygame Smudge Trails

pygame - 带 Pillow 的 Python 3.3 - 导入错误 : No module named 'Image'

python - 如何显示文字?

python - pygame 搞砸了 ctypes