首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >p5.js中两种不同形状物体的碰撞检测

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

Stack Overflow用户
提问于 2017-07-04 10:09:20
回答 1查看 1.2K关注 0票数 2

我试图让我的粒子物体碰撞和反射我的板岩物体。

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

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

代码语言:javascript
运行
AI代码解释
复制
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);
    }

  }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-04 10:18:25

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

代码语言:javascript
运行
AI代码解释
复制
if(pointX > rectX && pointX < rectX + rectWidth && pointY > rectY && pointY < rectY + rectHeight){
  //the point is inside the rectangle
}

如果粒子是椭圆,你需要考虑这个椭圆的半径,那么你最好把粒子表示为矩形,只是为了碰撞的目的。然后可以使用矩形-矩形碰撞检测。这也被称为边界框,它是处理碰撞检测的最常见的方法之一。

代码语言:javascript
运行
AI代码解释
复制
if(rectOneRight > rectTwoLeft && rectOneLeft < rectTwoRight && rectOneBottom > rectTwoTop && rectOneTop < rectTwoBottom){
  //the rectangles are colliding
}

无耻的自我推销:我写了一个关于碰撞检测可用的这里教程。它是用于处理的,但是对于P5.js,一切都是一样的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44911966

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档