代码之家  ›  专栏  ›  技术社区  ›  Benjamin Gibbs710

p5.js中两个不同形状物体的碰撞检测

  •  2
  • Benjamin Gibbs710  · 技术社区  · 8 年前

    我试图让我的粒子对象碰撞并反射到我的板岩对象上。

    如果我想用一个椭圆,它会很简单,因为我可以创建一个半径变量-不能用一个矩形。

    这和距离变量有关,我就是搞不懂。

    var div;
    var movers;
    
    
    function setup() {
      createCanvas(windowWidth,windowHeight);
      background("#FDEDEB");
      div = new Slate();
      movers = new Particle();
    }
    
    function draw() {
    
      background("#FDEDEB");
    
      div.display();
    
      movers.display();
      movers.update();
      movers.move();
    
      if (movers.hits(div)) {
        console.log("hit");
      }
    
    }
    
    
    function Slate() {
    
      this.x = 30;
      this.y = height/2;
    
      this.display = function() {
      noStroke();
      fill("#DF4655");
      rect(this.x,this.y, 700, 200);
    
      }
    }
    
    function Particle() {
      this.pos = createVector(10,0);
      this.vel = createVector(0,0);
      this.acc = createVector(0.01,0.01);
      this.history = [];
    
      this.display = function() {
        fill("#DF4655");
        point(this.pos.x,this.pos.y);
    
        //beginShape();
        for(var j = 0; j < this.history.length; j++) {
          var pos = this.history[j];
          ellipse(pos.x,pos.y, 5, 3);
        }
        //endShape();
    
      }
    
      this.update = function() {
    
        var v = createVector(this.pos.x,this.pos.y);
        this.history.push(v);
        if (this.history.length > 10) {
          this.history.splice(0,1);
        }
      }
    
      this.hits = function(div) {
            // BOUNCE OFF SLATE
          var d = dist(this.pos.x,this.pos.y,div.x,div.y);
          if (d < 0) {
            console.log('hits');
          }
      }
    
    
      this.move = function() {
    
        this.pos.add(this.vel);
        this.vel.add(this.acc);
        this.vel.limit(10);
    
        for (var i = 0; i < this.history.length; i++) {
          this.history[i].x += random(-2,2);
          this.history[i].y += random(-2,2);
        }
    
      }
    }
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Kevin Workman    8 年前

    如果粒子是点(或可以表示为点),则需要使用点-矩形碰撞检测。基本上,您需要检查点是否位于矩形的左边缘和右边缘以及上边缘和下边缘之间。

    if(pointX > rectX && pointX < rectX + rectWidth && pointY > rectY && pointY < rectY + rectHeight){
      //the point is inside the rectangle
    }
    

    如果粒子是椭圆,并且需要考虑椭圆的半径,那么最好将粒子表示为矩形,仅用于碰撞目的。然后可以使用矩形-矩形碰撞检测。这也称为边界框,是处理碰撞检测的最常用方法之一。

    if(rectOneRight > rectTwoLeft && rectOneLeft < rectTwoRight && rectOneBottom > rectTwoTop && rectOneTop < rectTwoBottom){
      //the rectangles are colliding
    }
    

    here