python - 如何使对象在pygame中移动,而不会使渲染变慢?
问题描述
我目前正在使用 pygame 设计一个应用程序,其中我有许多通过线条连接的圆圈,其中写有数字文本。这些圆圈是绿色、蓝色和红色的,而其他的都是黑色的。背景为白色。(把它想象成一个网络图)
我的目标:我正在尝试运行动画,其中用户选择两个圆圈(让我们称它们为节点),并找出发送者节点(绿色)到接收者节点(红色)之间的最短路径。所以在这个动画中,我在连接两个相邻节点(这些可能是中间节点)的线(或边)的顶部制作了另一个移动圆圈。
到目前为止一切都很好,这是我正在做的代码:
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:更新屏幕上的所有内容(当然它没有给我很好的表现)
- 选项 2:仅更新实际使用的屏幕部分。但是,即使使用这种方法,我也无法获得良好的屏幕更新性能。我想稍后添加一个功能来控制动画的速度,它的速度可能比我现在代码的最大性能还要快!
正如你所看到的,我现在还没有time.sleep()
。我想提高我的代码的性能,然后能够添加time.sleep()
一个更受控制的动画。multiprocessing
我当前的 pygame 应用程序已经与我使用库实现的另一个进程并行运行。
问题:如何让它更快?
我的python版本:3.7.0,pygame版本:1.9.6
PS:抱歉问题的长度
解决方案
尝试使用
pygame.time.Clock().tick(**)
这是一个命令,允许您选择要运行程序的 FPS,从而提高渲染速度。如果您决定使用它,请在我写星号的地方输入一个表示 FPS 的整数。
推荐阅读
- pine-script - 使用 pine 脚本使用 label.new 打印一个值
- java - 为什么 Getter 和 Setter 不适用于 Android 中的 Arraylist
- rest - BizTalk 休息 HTTP 201 处理
- r - 如何处理提取链接中的空格(rvest)
- angular - Angular 9,如何过滤具有包含点和斜线值的列的表?
- postgresql - Postgres 和 TypeORM WHERE 子句过滤 JOIN 表
- azure - 将 DataStage 作业迁移到 ADF,需要订阅和任何插件
- json - 如何验证 jsonschema 中的变量嵌套对象?
- node.js - 我无法为 vue.js 运行任何命令
- flutter - Flutter:我的 Listview.builder 消失在我的固定底部容器下