Ejemplo n.º 1
0
    // Handles all ball-ball collisions
    void handleBallBallCollisions() {

      for (int i = 0; i < _scene.numChildren(); i++)
        for (int j = 0; j < _scene.numChildren(); j++) {

          if (i == j) continue;

          Object3d b1 = _scene.getChildAt(i);
          Object3d b2 = _scene.getChildAt(j);

          // if (b1 == _room || b2 == _room)
          // continue;

          if (testBallBallCollision(b1, b2)) {
            // Make the balls reflect off of each other

            Number3d displacement = Number3d.subtract(b1.position(), b2.position());
            displacement.normalize();
            float objDot = Number3d.dot(b1.velocity(), displacement);
            displacement.multiply(objDot);
            displacement.multiply(2f);
            b1.velocity().subtract(displacement);

            displacement = Number3d.subtract(b1.position(), b2.position());
            displacement.normalize();
            objDot = Number3d.dot(b2.velocity(), displacement);
            displacement.multiply(objDot);
            displacement.multiply(2f);
            b2.velocity().subtract(displacement);
          }
        }
    }
Ejemplo n.º 2
0
 // Returns whether two balls are colliding
 boolean testBallBallCollision(Object3d obj1, Object3d obj2) {
   // Check whether the balls are close enough
   float r = obj1.radius() + obj2.radius();
   Number3d obj1Clone = Number3d.subtract(obj1.position(), obj2.position());
   obj1Clone.subtract(obj2.position());
   if (obj1Clone.magnitudeSquared() < r * r) {
     // Check whether the balls are moving toward each other
     Number3d netVelocity = Number3d.subtract(obj1.velocity(), obj2.velocity());
     Number3d displacement = Number3d.subtract(obj1.position(), obj2.position());
     return Number3d.dot(netVelocity, displacement) < 0;
   } else return false;
 }