简体   繁体   English

在 Pygame、Python 3 中设置固定 FPS

[英]Setting a fixed FPS in Pygame, Python 3

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.我目前正在使用 PyGame (Python 3) 制作游戏,并且正在寻找一种使游戏以固定 FPS 运行的方法。

Most of the game is located inside a giant while loop, where the user input is taken, sprites are rendered, etc. every tick.游戏的大部分内容都位于一个巨大的 while 循环中,在每个滴答声中,用户输入被获取,精灵被渲染等等。 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.我的目标是能够设置一个固定的 FPS,使游戏在快速或慢速的计算机上以相同的速度运行。

I can, of course, use the clock module in pygame:我当然可以在 pygame 中使用时钟模块:

clock = pygame.time.Clock()

and then call this every loop:然后在每个循环中调用它:

clock.tick(30)

but that will keep the game CAPPED at 30 FPS.但这将使游戏保持在 30 FPS 的上限。 So if I set it to 500 FPS it might still run as fast as it did before.因此,如果我将其设置为 500 FPS,它可能仍会像以前一样快速运行。 My goal is that if I set it to 500 FPS it will run at the same SPEED as it would at 500 FPS...我的目标是,如果我将其设置为 500 FPS,它将以与 500 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?那么是否有可能让游戏以固定的 FPS 运行(或产生一种错觉),而不管计算机的速度如何——或者至少通过使用某些跳帧算法以相同的速度运行?

Sorry if that wording was rather confusing.对不起,如果那个措辞相当混乱。

The clock.tick returns the time since the last call to clock.tick. clock.tick 返回自上次调用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

This way your player will always move at the same speed independent of what you put into the clock.tick() function.这样,您的播放器将始终以相同的速度移动,而与您在clock.tick()函数中输入的内容clock.tick()

Important is to only call clock.tick() once per frame.重要的是每帧只调用一次clock.tick()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM