我有一个空数组,它在每次更新时都会添加新元素。这些是从屏幕顶部到底部的三角形。我该如何让这些三角形相互作用呢。我希望它们相互碰撞,但我找到的每一个教程都没有帮助。
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>
1条答案
按热度按时间mi7gmzs61#
我自己不使用p5,但对于任何库,基本原理都是一样的:测试每个对象是否与另一个对象重叠,并在发生重叠时采取一些措施:例如,改变一个或两个对象的位置,使它们不再碰撞。
a看一下主屏幕
p5.js
库显示它有一个名为p5.collide2d
你可以用的。此库具有用于检查两个多边形是否相交的函数collidepolypoly()。这是一个官方演示,检查随机放置的圆圈的碰撞。如果一个新添加的圆与另一个圆重叠,则会给它一个新的位置,并重复该测试,直到所有圆都放置在没有任何重叠的位置-相同类型的想法。
https://editor.p5js.org/p52dcollide/sketches/wyb8vt3mh
或者您可能想使用
p5.play
取而代之的是图书馆。下面是一个对象相互反弹的示例http://molleindustria.github.io/p5.play/examples/index.html?filename=collisions4.js