在 Pygame、Python 3 中设置固定 FPS [英] Setting a fixed FPS in Pygame, Python 3

查看:40
本文介绍了在 Pygame、Python 3 中设置固定 FPS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用 PyGame (Python 3) 制作游戏,我正在寻找一种方法让游戏以固定的 FPS 运行.

I'm currently making a game using PyGame (Python 3), and I'm looking for a way to make the game run at a fixed FPS.

游戏的大部分内容都位于一个巨大的 while 循环中,在每个滴答声中,用户输入被获取,精灵被渲染等等.我的目标是能够设置一个固定的 FPS,使游戏在快速或慢速的计算机上以相同的速度运行.

Most of the game is located inside a giant while loop, where the user input is taken, sprites are rendered, etc. every tick. My goal is to be able to set a fixed FPS that will make the game run at the same speed on a fast or slow computer.

我当然可以在 pygame 中使用时钟模块:

I can, of course, use the clock module in pygame:

clock = pygame.time.Clock()

然后在每个循环中调用它:

and then call this every loop:

clock.tick(30)

但这将使游戏保持在 30 FPS 的上限.因此,如果我将其设置为 500 FPS,它可能仍会像以前一样快速运行.我的目标是,如果我将其设置为 500 FPS,它将以与 500 FPS 相同的速度运行...

but that will keep the game CAPPED at 30 FPS. So if I set it to 500 FPS it might still run as fast as it did before. My goal is that if I set it to 500 FPS it will run at the same SPEED as it would at 500 FPS...

那么是否有可能让游戏以固定的 FPS 运行(或产生一种错觉),而不管计算机的速度如何 - 或者至少通过使用某些跳帧算法以相同的速度运行?

So is it possible to make the game run at a fixed FPS (or make an illusion of that), regardless of the speed of the computer - or at least run at the same speed through the use of some frame-skip algorithm?

抱歉,措辞有点令人困惑.

Sorry if that wording was rather confusing.

推荐答案

clock.tick 返回自上次调用clock.tick 以来的时间.移动时使用该值并将所有速度乘以它.示例

The clock.tick returns the time since the last call to clock.tick. Use that value and multiply all your speeds with it when you move. Example

dt = clock.tick(60)
player.position.x += player.xSpeed * dt
player.position.y += player.ySpeed * dt

这样您的播放器将始终以相同的速度移动,而与您在 clock.tick() 函数中输入的内容无关.

This way your player will always move at the same speed independent of what you put into the clock.tick() function.

重要的是每帧只调用一次 clock.tick().

Important is to only call clock.tick() once per frame.

这篇关于在 Pygame、Python 3 中设置固定 FPS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆