P5JS-绘制不重叠的圆圈

问题描述 投票:0回答:1

我有这段代码来绘制一个圆数组并确保它们不会重叠。我不知道我的问题是什么,因为它没有给出错误,但同时,我也没有看到任何事情发生。

class particle{
  constructor(x,y,r){
    this.x=x;
    this.y=y;
    this.r=r;

  }
  
  show(){
    noFill();
    stroke(0);
    strokeWeight(1);
    ellipse(this.x,this.y,this.r);
  }
}

let circles=[];

function setup() {
  createCanvas(600, 400);
  
  for (let i=0; i<25; i++){
    let x=random(width);
    let y=random(height);
    let r=50;
    circles[i]= new particle(x,y,r);  
    
  let overlap=false;
    for (let j=0; j<circles.length; j++){
      let other=circles[j];
      let circle=circles[i];
      let d=dist( circle.x,circle.y,other.x,other.y);
      if ( d < circle.r/2 + other.r/2){
        overlap=true;
      }
      
      if (!overlap){
        circles.push(circle);
      }
    }
    circles[i].show();
  }
}

function draw() {
  background(220);
}
javascript class p5.js
1个回答
0
投票

draw()
setup()
运行一次之后每秒运行约 60 次。
background(220);
将整个画布擦拭干净,立即覆盖您在
setup()
中绘制的圆形。

两种可能的解决方案,具体取决于您是否想要动画:

  1. draw()
    调用之后,将粒子绘制代码移至
    background()
    。将在每一帧上重新绘制粒子,以用于动画。
  2. 完全删除
    draw()
    ,只需绘制一次粒子即可。

这是选项 2:

class Particle {
  constructor(x, y, r) {
    this.x = x;
    this.y = y;
    this.r = r;
  }

  show() {
    noFill();
    stroke(0);
    strokeWeight(1);
    ellipse(this.x, this.y, this.r);
  }
}

let circles = [];

function setup() {
  createCanvas(600, 400);

  for (let i = 0; i < 25; i++) {
    let x = random(width);
    let y = random(height);
    let r = 50;
    circles[i] = new Particle(x, y, r);

    let overlap = false;
    for (let j = 0; j < circles.length; j++) {
      let other = circles[j];
      let circle = circles[i];
      let d = dist(circle.x, circle.y, other.x, other.y);
      if (d < circle.r / 2 + other.r / 2) {
        overlap = true;
      }

      if (!overlap) {
        circles.push(circle);
      }
    }
    circles[i].show();
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.9.0/p5.js"></script>

请注意,我使用了 prettier 自动格式化代码并将类名大写。

© www.soinside.com 2019 - 2024. All rights reserved.