首页 > 解决方案 > 如何在没有球反弹的情况下模拟球与球的碰撞?

问题描述

我正在尝试制作一个简单的球物理模拟器,其中球与彼此和墙壁发生碰撞。前者是我正在努力解决的问题。我希望球相互碰撞但不反弹,我只想让它们不会进入彼此内部。

代码的更多相关位:

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/

标签: javascriptcollision-detectionphysicsp5.js

解决方案


就像威廉米勒所说,你希望他们做什么而不是反弹?您可以简单地将它们分开半径 + 另一个半径。

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 );

           }
      }
 }

推荐阅读