首页 > 解决方案 > 如何使对象在pygame中移动,而不会使渲染变慢?

问题描述

我目前正在使用 pygame 设计一个应用程序,其中我有许多通过线条连接的圆圈,其中写有数字文本。这些圆圈是绿色、蓝色和红色的,而其他的都是黑色的。背景为白色。(把它想象成一个网络图)

我的目标:我正在尝试运行动画,其中用户选择两个圆圈(让我们称它们为节点),并找出发送者节点(绿色)到接收者节点(红色)之间的最短路径。所以在这个动画中,我在连接两个相邻节点(这些可能是中间节点)的线(或边)的顶部制作了另一个移动圆圈。

例如,圆在这里从节点 2 移动到节点 11

到目前为止一切都很好,这是我正在做的代码:

def runPathAnimation(path, colortype):
    for i in range(len(path)-1):
        #Calculation of the center of the nodes
        x1, y1 = (gmd[path[i]].getNodePosition())[0], (gmd[path[i]].getNodePosition())[1]
        x2, y2 = (gmd[path[i+1]].getNodePosition())[0], (gmd[path[i+1]].getNodePosition())[1]
        #Get the slope
        m = (y1-y2)/(x1-x2) if x1 != x2 else 'undefined'
        if str(m) != 'undefined':
            c = y2-(m*x2)
            if m > 0.5 or (m <= -1 and m >= -1.5):
                for y in range(min(y1,y2),max(y1,y2)):
                    #using the equation of the line
                    x = int((y-c)/m)
                    #redrawEverything(path)                                     #OPTION 1
                    #TRY REDRAW LINE                                            #TODO
                    pyg.draw.rect(screen, (255, 255, 255), (x-10,y-10,20,20))   #OPTION 2
                    pyg.draw.circle(screen, colortype, (x,y), 10)               #Moving circle
                    pyg.display.update()                                        #Update Display
                    #NEED: Redraw!
            #The logic repeats....
            else:
                for x in range(min(x1,x2),max(x1,x2)):
                    y = int(m*x+c)
                    #redrawEverything(path)
                    #TRY REDRAW LINE
                    pyg.draw.rect(screen, (255, 255, 255), (x-10,y-10,20,20))
                    pyg.draw.circle(screen, colortype, (x,y), 10)
                    pyg.display.update()
                    #NEED: Redraw!
        else:
            cy = range(min(y1,y2),max(y1,y2))
            if y1 > y2:
                cy = reversed(cy)
            for y in cy:
                #redrawEverything(path)
                #TRY REDRAW LINE
                pyg.draw.rect(screen, (255, 255, 255), (x1-10,y-10,20,20))
                pyg.draw.circle(screen, colortype, (x1,y), 10)
                pyg.display.update()
                #NEED: Redraw!

我的问题:我用另一个位置简单地更新一个圆圈的方法有很多滞后,而不会干扰它所覆盖的任何东西。我有两个选择:

  1. 选项 1:更新屏幕上的所有内容(当然它没有给我很好的表现)
  2. 选项 2:仅更新实际使用的屏幕部分。但是,即使使用这种方法,我也无法获得良好的屏幕更新性能。我想稍后添加一个功能来控制动画的速度,它的速度可能比我现在代码的最大性能还要快!

正如你所看到的,我现在还没有time.sleep()。我想提高我的代码的性能,然后能够添加time.sleep()一个更受控制的动画。multiprocessing我当前的 pygame 应用程序已经与我使用库实现的另一个进程并行运行。

问题:如何让它更快?

我的python版本:3.7.0,pygame版本:1.9.6

PS:抱歉问题的长度

标签: pythonpython-3.xgraphicspygamemultiprocessing

解决方案


尝试使用 pygame.time.Clock().tick(**) 这是一个命令,允许您选择要运行程序的 FPS,从而提高渲染速度。如果您决定使用它,请在我写星号的地方输入一个表示 FPS 的整数。


推荐阅读