javascript - p5.j​​s 中两个不同形状的物体碰撞检测

标签 javascript object collision-detection p5.js

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

如果我想使用椭圆形,那会很简单,因为我可以创建一个半径变量 - 不能用矩形来做到这一点。

这与距离变量有关,我只是无法弄清楚。

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);
    }

  }
}

最佳答案

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

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
}

无耻的 self 推销:我写了一篇关于碰撞检测的教程可用here 。它用于处理,但 P5.js 的一切都是相同的。

关于javascript - p5.j​​s 中两个不同形状的物体碰撞检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44911966/

相关文章:

3d - XNA 3d 物理引擎

box2d - 缩放 Box2D 圆形形状及其碰撞检测?

javascript - 删除主干模型上的一堆属性

javascript - 如何遍历对象数组并计算存在多少个重复值?

android - 碰撞检测和碰撞响应

java - 在一个类中构建对象并在另一个类中访问它们

Objective-C:类别中的实例变量

javascript - Ajax上传图片

javascript - requestFullscreen() 在不安全的来源上被弃用,并且将来会删除支持

javascript - 无法获取 navigator.notification.alert ("test")在 Phonegap android 应用程序上工作