用Python语言编写游戏循环的正确方式是什么? [英] What's the proper way to write a game loop in Python?
本文介绍了用Python语言编写游戏循环的正确方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个Python游戏循环,希望它能考虑FPS。调用循环的正确方式是什么?我考虑过的一些可能性如下。我正在努力不使用像pyGame这样的库。
1.
while True:
mainLoop()
2.
def mainLoop():
# run some game code
time.sleep(Interval)
mainLoop()
3.
def mainLoop():
# run some game code
threading.timer(Interval, mainLoop).start()
4. 使用Schedul.Scheduler?
推荐答案
如果我理解正确的话,您希望将游戏逻辑基于时间增量。
尝试获取每一帧之间的时间增量,然后让对象相对于该时间增量移动。
import time
while True:
# dt is the time delta in seconds (float).
currentTime = time.time()
dt = currentTime - lastFrameTime
lastFrameTime = currentTime
game_logic(dt)
def game_logic(dt):
# Where speed might be a vector. E.g speed.x = 1 means
# you will move by 1 unit per second on x's direction.
plane.position += speed * dt;
如果您还想限制每秒的帧数,一种简单的方法是在每次更新后休眠适当的时间。
FPS = 60
while True:
sleepTime = 1./FPS - (currentTime - lastFrameTime)
if sleepTime > 0:
time.sleep(sleepTime)
请注意,只有当您的硬件对您的游戏足够快时,这才会起作用。有关游戏循环的更多信息,请查看this。
PS)抱歉,使用了Java变量名...刚从一些Java编码中休息了一下。
这篇关于用Python语言编写游戏循环的正确方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文