我的 p5.js 代码滞后,我不知道为什么?

My p5.js code is lagging i dont know why?

我试图在按下鼠标时移动圆圈的同时进行绘制。但最终,当我在一段时间后移动它时,旋转的圆圈和大圆圈会变慢。 我不知道是什么原因,我以为是因为列表是用坐标累加的,最终导致代码滞后,请帮助。

如果您按下鼠标并等待一段时间,您会发现圆圈最终变慢了。如果我错了,请纠正我。

class Particle{
  constructor(){
    this.center = createVector(0,0);
    this.radius = 20;
    this.theta = 0;
    this.line = createVector(0,0);
    this.history = [];
    this.velocity = createVector();

    

  }
  
  render(){
    translate(60,60);
    circle(this.center.x,this.center.y,this.radius);
    
    
    circle(this.line.x+this.center.x, this.line.y+this.center.y,10); 

    beginShape();
    for(let i=0;i < this.history.length; i++){
      let pos = this.history[i];
      noFill();
      vertex(pos.x, pos.y);
      endShape();
    }

    }
  

  update(){
    this.line.x = this.radius*cos(this.theta);
    this.line.y = this.radius*sin(this.theta);
    
    
    
    if (mouseIsPressed){
      this.center.x = (1-0.025)*this.center.x + 0.025*(this.line.x + this.center.x);
      this.center.y = (1-0.025)*this.center.y + 0.025*(this.line.y + this.center.y);


    let v = createVector(this.center.x, this.center.y);
    this.history.push(v);

    
      } else{

        this.theta += 0.01;
      } 
    
    


  }
 }
 
let particle;


function setup() {
  
  createCanvas(windowWidth, windowHeight);
  
  particle = new Particle();
}

function draw() {
  background(220);
  particle.render();
  particle.update();
  
  
}
<html>
  <body>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.2.0/p5.js"></script>
  </body>
</html>

您的代码中 beginShape()endShape() 未对齐。 beginShape() 在循环之前,但 endShape() 在循环中。在循环后移动endShape()

beginShape();
for(let i=0;i < this.history.length; i++){
    let pos = this.history[i];
    noFill();
    vertex(pos.x, pos.y);
}
endShape();

代码很可能滞后,因为历史记录中的点数增加了。尽量减少点数。像素只能显示在整数位置。避免向列表中添加重复项:


update(){
    this.line.x = this.radius*cos(this.theta);
    this.line.y = this.radius*sin(this.theta);

    if (mouseIsPressed){
        this.center.x = (1-0.025)*this.center.x + 0.025*(this.line.x + this.center.x);
        this.center.y = (1-0.025)*this.center.y + 0.025*(this.line.y + this.center.y);
        let v = createVector(this.center.x, this.center.y);
        
        let h = this.history;
        if (h.length == 0 || 
            Math.trunc(h[h.length-1].x) != Math.trunc(v.x) || 
            Math.trunc(h[h.length-1].y) != Math.trunc(v.y)) { 
            
            this.history.push(v);
        }
    
    } else{
        this.theta += 0.01;
    } 
}

如果应用程序仍然滞后,您可以尝试在大小为 canvas (createGraphics()) 的 p5.Renderer 对象上绘制点。将此对象绘制在 canvas 上作为背景图像。