Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
730 views
in Technique[技术] by (71.8m points)

performance - 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.

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.

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

clock = pygame.time.Clock()

and then call this every loop:

clock.tick(30)

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...

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...