【问题标题】:Pygame Image Movement AnomalyPygame 图像移动异常
【发布时间】:2018-09-02 09:30:14
【问题描述】:

我正在使用 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 的新手。我有什么明显的遗漏吗?

【问题讨论】:

    标签: python pygame


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多