Как мне имитировать столкновение шара с мячом, не отскакивая? - PullRequest
0 голосов
/ 11 апреля 2020

Я пытаюсь создать простой симулятор физики шаров, в котором шары сталкиваются друг с другом и со стенами. С первым я борюсь. Я хочу, чтобы шары сталкивались друг с другом, но не отскакивали, я просто хочу сделать так, чтобы они не попадали внутрь друг друга.

Более соответствующие биты кода:

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/

1 Ответ

2 голосов
/ 13 апреля 2020

Как Уильям Миллер говорит: что вы хотите, чтобы они делали, а не отскакивали? Вы можете просто разделить их на радиус + другой радиус.

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

           }
      }
 }
...