由网友(沵不是姐的菜)分享简介:我正在尝试编写一个Python游戏循环,希望它能考虑FPS。调用循环的正确方式是什么?我考虑过的一些可能性如下。我正在努力不使用像pyGame这样的库。1.while True:mainLoop()2.def mainLoop():# run some game codetime.sleep(Interval)main...![如何使用python语言中的方法获取字典中的值](https://p.xsw88.cn/allimgs/daicuo/20230903/2597.png)
我正在尝试编写一个Python游戏循环,希望它能考虑FPS。调用循环的正确方式是什么?我考虑过的一些可能性如下。我正在努力不使用像pyGame这样的库。
1.
while True:
mainLoop()
![如何使用python语言中的方法获取字典中的值](https://p.xsw88.cn/allimgs/daicuo/20230903/2597.png)
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编码中休息了一下。
相关推荐
最新文章