如何使精灵在 Pygame & 中的所有计算机上均匀移动Python

发布于 2025-01-05 19:45:21 字数 262 浏览 6 评论 0原文

我在均匀移动精灵时遇到问题;目前我正在使用 while 循环来移动它们,问题是计算机越快,循环越快,精灵移动得越快。我在 pygame 中尝试过计时器/时钟功能(等待?),它在等待时冻结光标,因此使光标跳动。

多线程是答案吗?

这是我的问题的视频; http://www.youtube.com/watch?v=cFawkUJhf30

I'm having a problem with evenly moving sprites; Currently I'm using a while loop to move them, the problem with this being the faster the computer, the faster the loop goes and the faster the sprites move. I have tried the timer / clock function (wait?) in pygame and it freezes the cursor while it waits, therefore maiking the cursor jumpy.

Is multi-threading the answer?

Here's a video of my problem;
http://www.youtube.com/watch?v=cFawkUJhf30

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

策马西风 2025-01-12 19:45:21

你依赖于帧速率,帧速率越快,你的移动就会越快。

通常,我们计算 2 帧/循环迭代之间的时间,我们将其称为“增量时间”。然后我们将该增量时间乘以运动向量。

这是一个循环示例:

clock = pygame.time.Clock()
while True:
    # limit the framerate and get the delta time
    dt = clock.tick(60)

    # convert the delta to seconds (for easier calculation)
    speed = 1 / float(dt)

    # do all your stuff, calculate your heroes vector movement
    # if heroes position is "px, py" and movement is "mx, my"
    # then multiply with speed
    px *= mx * speed
    py *= my * speed

然后运动遵循帧速率:如果循环更快,则增量更低,然后每帧的运动更慢 =>无论帧速率是多少,结果都将具有相同的速度。

您现在与帧速率无关。

You're dependent of the framerate, faster the framerate is, faster your movement will be.

Usually, we are calculating the time between 2 frames/loop iteration, and we called it the "delta time". Then we multiply that delta time to the movement vector.

Here is a loop sample:

clock = pygame.time.Clock()
while True:
    # limit the framerate and get the delta time
    dt = clock.tick(60)

    # convert the delta to seconds (for easier calculation)
    speed = 1 / float(dt)

    # do all your stuff, calculate your heroes vector movement
    # if heroes position is "px, py" and movement is "mx, my"
    # then multiply with speed
    px *= mx * speed
    py *= my * speed

Then the movement are following the framerate: if your loop is faster, then the delta is lower, and then the movement are slower per frame => the result will have the same speed whatever the framerate is.

You're now framerate independent.

云醉月微眠 2025-01-12 19:45:21

我在此处找到了一个处理此问题的线程:

尝试以下操作:

clock = pygame.time.Clock()
while True:
    if clock.tock(60): #Limit to 60fps
        ... #Update game display here
    else:
        cursor.update()

I found a thread dealing with this problem here:

Try the following:

clock = pygame.time.Clock()
while True:
    if clock.tock(60): #Limit to 60fps
        ... #Update game display here
    else:
        cursor.update()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文