首页 > 解决方案 > 如何使一组三角形相互碰撞?

问题描述

我有一个空数组,每次更新都会添加新元素。这些是从屏幕顶部到底部的三角形。我将如何使这些三角形相互作用。我希望它们相互碰撞,但我发现的每个教程都没有帮助。

let PARTICLES = [];
//Creates canvas of 400x650 pixels
function setup() {
  createCanvas(400, 650);
}

//Creates new particles and adds them to the Particles[] array
function draw() {
  background("turquoise");
  let newP = new Particle();
  PARTICLES.push(newP);
  //Continously +1 to the PARTICLES array which duplicated the original triangle.
  for (let i = 0; i < PARTICLES.length; i++) {
    PARTICLES[i].update();
    PARTICLES[i].show();
    if(PARTICLES[i].delete()) {
      PARTICLES.splice(i,1);           //keeps the array 78 elements long
    }
  }
}

//Gives the position of the original particle that all the others are copied from
class Particle {
  constructor() {
    this.x1 = 195;
    this.y1 = 30;
    this.x2 = 200;
    this.y2 = 20;
    this.x3 = 205;
    this.y3 = 30;
    this.vx = random(-0.8, 0.8);
    this.vy = 8;
  }
  
  //if the y position of a particle gets >650, it is deleted from the array
  delete() {
    return this.y1 > 650;
  }
  
  //updates every vertex with the speed given to it
  update() {
    this.x1 += this.vx;
    this.y1 += this.vy;
    this.x2 += this.vx;
    this.y2 += this.vy;
    this.x3 += this.vx;
    this.y3 += this.vy;  
  }
  
  //Triangle properties
  show() {
    stroke(255);
    fill(255, 10);
    triangle(this.x1, this.y1, this.x2, this.y2, this.x3, this.y3);
  }
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="p5.collide2D.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/addons/p5.sound.min.js"></script>
    <link rel="stylesheet" type="text/css" href="style.css">
    <meta charset="utf-8" />

  </head>
  <body>
    <script src="sketch.js"></script>
  </body>
</html>

标签: javascriptp5.js

解决方案


我自己不使用 p5,但任何库的基础都是相同的:测试每个对象是否与另一个对象重叠,并在发生这种情况时采取一些措施:例如,改变一个或两个对象的位置,使它们是不再碰撞。

查看主p5.js库会发现它有一个插件库p5.collide2d,您可以使用它。这个库有函数collidePolyPoly()来检查 2 个多边形是否相交。

这是一个官方演示,用于检查随机放置的圆圈的碰撞。如果一个新添加的圆圈与另一个圆圈重叠,它会被赋予一个新的位置,并重复测试,直到所有圆圈都被放置而没有任何重叠 - 相同类型的想法。

https://editor.p5js.org/p52dcollide/sketches/WYb8vT3Mh

或者您可能想改用该p5.play库。这是一个对象相互反弹的示例http://molleindustria.github.io/p5.play/examples/index.html?fileName=collisions4.js


推荐阅读