Как Уильям Миллер говорит: что вы хотите, чтобы они делали, а не отскакивали? Вы можете просто разделить их на радиус + другой радиус.
https://jsfiddle.net/EthanHermsey/n906fdmh/21/
collide() {
for (let p of particles) {
if (this != p && p5.Vector.dist(this.pos, p.pos) < this.r + p.r) {
//a vector pointing from the other point to this point
let directionVector = p5.Vector.sub( this.pos, p.pos );
//set the magnitude of the vector to the length of both radiusses
directionVector.setMag( this.r + p.r );
//now set this.pos at a fixed distance from p.pos. In the same direction as it was before.
this.pos = p.pos.copy();
this.pos.add( directionVector );
}
}
}
Также я переехал «this! = p» вперед, это немного быстрее, потому что вычисление расстояния не нужно сначала делать.
Эта функция расстояния в любом случае довольно медленная из-за вычисления квадратного root , вы можете попробовать использовать функцию magSq (), например так:
collide() {
for (let p of particles) {
if ( p == this ) continue; //go to the next particle
//a vector pointing from the other point to this point
let directionVector = p5.Vector.sub( this.pos, p.pos );
//pow( this.r + p.r, 2 ) is the same as ( this.r + p.r ) * ( this.r + p.r )
if ( this != p && directionVector.magSq() < pow( this.r + p.r, 2 ) ) {
//set the magnitude of the vector to the length of both radiusses
directionVector.setMag( this.r + p.r );
//now set this.pos at a fixed distance from p.pos. In the same direction as it was before.
this.pos = p.pos.copy();
this.pos.add( directionVector );
}
}
}