多个相交的正方形

时间:2019-07-11 08:44:47

标签: javascript processing p5.js

这是我之前在Changing color of intersecting area of squares

上一篇文章的延续

我能够使正方形的相交区域改变颜色。问题是我想要多个相交的正方形,而不是一个,所以我修改了代码。现在的问题是,广场在移动的任何地方都在绘制正方形,因此留下了痕迹。一段时间后,它开始变慢。我该如何克服

function draw() {

  background(135,206,250);
  myColour = (255); 

  // if a square is being dragged, update its position
  if (this.dragObject != null) {
    this.dragObject.position.x = mouseX;
    this.dragObject.position.y = mouseY;
  }

  //draw all squares
  for (let i = 0; i < squares.length; i++) {
    let s = squares[i];
    s.show();
  }

  for (let i = 0; i < squares.length; i++) {
    for (let j = i + 1; j < squares.length; j++) {
      //block checking collision
      if (i != j && squares[i].collides(squares[j])) {
        squares[i].changecolor();

        //set intersection color
        fill(myColour);

        //calculate parameters
        newX = Math.max(squares[i].position.x, squares[j].position.x);
        newY = Math.max(squares[i].position.y, squares[j].position.y);

        newW = Math.min(squares[i].position.x + squares[i].w, squares[j].position.x + squares[j].w) - newX;
        newH = Math.min(squares[i].position.y + squares[i].h, squares[j].position.y + squares[j].h) - newY;

        //draw rectangle
        let Osquare = new OverlappingSquares(newX, newY, newW, newH);
        overlappingsquares.push(Osquare);
      }
    }
  }
}
changecolor() {
    // fill(random(255), random(255), random(255));
    // background(200, 255, 100);
    for (let i = 0; i < squares.length; i++) {
      let s = squares[i];
      s.show();

    }
    for (let i = 0; i < overlappingsquares.length; i++) {
      let s = overlappingsquares[i];
      s.show();

    }
  }
//Overlapping sqaures class
class OverlappingSquares {
  constructor(X, Y, W, H) {
    this.w = W;
    this.h = H;
    this.position = {
      x: X,
      y: Y
    };
  }
  show() {
    fill(myColour)
    rect(this.position.x, this.position.y, this.w, this.h);
  }
}

0 个答案:

没有答案