簡體   English   中英

我的 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;
    } 
}

如果應用程序仍然滯后,您可以嘗試在 p5.Renderer object 上繪制與 canvas 大小相同的點( createGraphics createGraphics() )。 在 canvas 上繪制這個 object,就像背景圖像一樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM