gpt4 book ai didi

python - Pygame 图像移动异常

转载 作者:太空宇宙 更新时间:2023-11-04 02:29:59 24 4
gpt4 key购买 nike

我正在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com