我正在尝试制作一个简单的球物理模拟器,使球彼此碰撞并与墙壁碰撞。前者是我一直在努力的那个。我希望球彼此碰撞但不反弹,我只是想使它们不会彼此碰撞。
代码的更多相关位:
class Particle {
constructor(x, y) {
this.pos = createVector(x, y);
this.vel = p5.Vector.random2D();
this.vel.setMag(4)
this.r = 20
}
collide() {
for (let p of particles) {
if (p5.Vector.dist(this.pos, p.pos) < this.r + p.r && this != p) {
//Collide
}
}
}
}
JSFIDDLE:https://jsfiddle.net/7oh3p4ku/1/
[就像威廉·米勒(William Miller)所说,您希望他们做什么而不是反弹呢?您可以简单地将它们相隔半径+其他半径。
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'移到了前面,这快了一点,因为不必先进行距离计算。
由于平方根计算,该距离函数还是很慢的,您可以像这样尝试使用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 );
}
}
}