如何解决Python Pyglet减慢了动画的速度在屏幕上缓慢绘制对象
我反复遇到了在Python中绘制各种对象时放慢动画速度的问题。当要绘制的对象数量增加时,该问题尤其严重。我不会说对象太多了:> = 200(r = 10)个圆圈已经是幻灯片。
我认为这与我使用的库无关(pyglet)。在此之前,我使用了p5py类似的p5.js刹车效果更强(实际上,p5py的创建者知道它比同类的Issues from Github慢得多)。我也尝试过Tkinter-我认为干净的画布可以解决我的问题。但是那没有发生。现在,我在Pyglet中运行代码-我得到了幻灯片。
我还注意到,当动画速度变慢时,计算机开始根据冷却器的喷射推力起飞。同时,Python进程的CPU负载永远不会超过20%(非常奇怪)。计算机不是计算器:英特尔i5-8300H 4核(8个虚拟)2.30 GHz 。
可能是什么问题?即使是Python,1000点的动画也不应变成幻灯片。
PS。我也认为问题不在我的代码中。确实,p5.js上的same(与下面的代码无关)代码在浏览器中提供了平滑的动画(但浏览器使用了视频卡)。但是,以防万一,我把最后的精力放在了Pyglet上-这不是优化的重中之重,但它应该不会如此缓慢地工作:
sketch.py
import pyglet
import random
from firework import Firework
window = pyglet.window.Window(400,400)
main_batch = pyglet.graphics.Batch()
fireworks = [Firework(main_batch)]
@window.event
def on_draw():
window.clear()
main_batch.draw()
def update(dt):
if random.random() < 0.03:
fireworks.append(Firework(main_batch))
for f in fireworks:
f.update()
if f.done():
fireworks.remove(f)
if __name__ == '__main__':
pyglet.clock.schedule_interval(update,1 / 120.0)
pyglet.app.run()
particle.py
import p5
import pyglet
class Particle(pyglet.shapes.Circle):
def __init__(self,x,y,color,firework,batch=None):
radius = 2
if firework:
radius = 4
super().__init__(x,radius,radius * 5,batch)
self.color = color
self.firework = firework
self.opacity = 255
self._done = False
self.acc = p5.Vector(0,0)
if self.firework:
self.vel = p5.Vector(0,p5.random_uniform(8,12))
else:
self.vel = p5.Vector.random_2D() * p5.random_uniform(-10,-2)
@property
def batch(self):
return self._batch
def update(self):
self.acc += p5.Vector(0,-0.2)
if not self.firework:
self.vel *= 0.9
if self.opacity > 4:
self.opacity -= 4
else:
self._done = True
self.opacity = 0
self.vel += self.acc
pos = p5.Vector(self.x,self.y) + self.vel
self.x = pos.x
self.y = pos.y
self.acc *= 0
def done(self):
return self._done
firework.py
import p5
import random
from particle import Particle
class Firework:
def __init__(self,batch):
self.color = tuple(random.randint(0,255) for _ in range(3))
self.firework = Particle(p5.random_uniform(400),self.color,True,batch=batch)
self.bach = batch
self._exploded = False
self.particles = []
def done(self):
if self._exploded and len(self.particles) == 0:
return True
else:
return False
def explode(self):
for _ in range(70):
p = Particle(self.firework.x,self.firework.y,False,batch=self.firework.batch)
self.particles.append(p)
def update(self):
if not self._exploded:
self.firework.update()
if self.firework.vel.y < 0:
self._exploded = True
self.explode()
self.firework.delete()
for p in self.particles:
p.update()
if p.done():
self.particles.remove(p)
p.delete()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。