我正在尝试编写一个希望考虑 FPS 的 python 游戏循环。调用循环的正确方法是什么?我考虑过的一些可能性如下。我尽量不使用像 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. 使用 sched.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 - 用 Python 编写游戏循环的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16301193/