如何防止2个组件重叠

时间:2019-02-22 13:56:06

标签: javascript p5.js

如何防止2个组件重叠,请帮助我使它们跟随Mouse而不重叠。我不是编码专家,请用简单的语言解释。

function component(x,y,r) {
       var randomcolor = ["violet","indigo","blue","green","yellow","orange","red"];
    this.pos=createVector(x,y);
    this.r=r;
    this.color=randomcolor[Math.floor(Math.random()*randomcolor.length)];
    this.show=function() {
     fill(this.color);
      stroke(241,241,241);
     ellipse(this.pos.x,this.pos.y,this.r*2,this.r*2);
    }
    this.crash = function(other) {
      var d = p5.Vector.dist(this.pos,other.pos);
    if (d<this.r+other.r) {
      this.r+=other.r/20;
      return true;}

}
    
    this.move=function(){
      this.pos.x=lerp(this.pos.x,mouseX,0.1);
      this.pos.y=lerp(this.pos.y,mouseY,0.1);
this.pos.x = constrain(this.pos.x,this.r,width-this.r)
this.pos.y = constrain(this.pos.y,this.r,height-this.r)

}    
}

1 个答案:

答案 0 :(得分:1)

要使多个对象移动而不会碰到彼此,则需要

  • 跟踪所有对象的当前位置
  • 能够识别每个对象,以使碰撞方法不会检测到对象与其自身的碰撞
  • 在尝试移动物体之前进行检查以确保不会发生碰撞

对于您的示例代码,这是一种使多个组件向鼠标移动而不会彼此碰到的一种可能性。我重写了崩溃函数,并添加了一些全局变量。这不是很优雅,但我认为它以一种您可以理解如何解决此类问题的方式回答了您的问题。

var ids = 0;
var allComponents = [];
function setup(){
  createCanvas(600,600);
  new component(10,10,10);
  new component(590,10,10);
}

function draw(){
   background(255);
   for (let i = 0; i < allComponents.length; i++){
     allComponents[i].show();
     allComponents[i].move();
   }
}
function component(x,y,r) {
    var randomcolor = ["violet","indigo","blue","green","yellow","orange","red"];
    this.pos=createVector(x,y);
    this.r=r;
    this.id = ids++;
    allComponents[allComponents.length] = this;         
    this.color=randomcolor[Math.floor(Math.random()*randomcolor.length)];
    this.show=function() {
      fill(this.color);
      stroke(241,241,241);
      ellipse(this.pos.x,this.pos.y,this.r*2,this.r*2);
    }
    this.crash = function(other) {
      var d = p5.Vector.dist(this.pos,other.pos);
      if (d< this.r + other.r) {
        return true;
      }
      return false;
    }
    
    this.move=function(){
      let originalX = this.pos.x;
      let originalY = this.pos.y;
      this.pos.x=lerp(this.pos.x,mouseX,0.1);
      this.pos.y=lerp(this.pos.y,mouseY,0.1);
      this.pos.x = constrain(this.pos.x,this.r,width-this.r);
      this.pos.y = constrain(this.pos.y,this.r,height-this.r);
      for (let i = 0; i < allComponents.length; i++){
        let other = allComponents[i];
        if (this.id !== other.id && this.crash(other)){
          this.pos.x = originalX;
          this.pos.y = originalY;
          break;
        }
      }  
    }    
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.min.js"></script>