在Pygame,Python 3中设置固定的FPS [英] Setting a fixed FPS in Pygame, Python 3
问题描述
我目前正在使用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 regardless of what you put into the clock.tick()
function.
要记住的重要一点是每帧只调用一次clock.tick()
.
Important to remember is to only call clock.tick()
once per frame.
这篇关于在Pygame,Python 3中设置固定的FPS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!