Guest

Untitled

By: a guest on Feb 23rd, 2009  |  syntax: Java  |  size: 1.51 KB  |  hits: 89  |  expires: Never
download  |  raw  |  embed  |  report abuse
Copied
  1. public void resolveCollision(Ball ball)
  2.         {
  3.  
  4.                 // get the mtd
  5.                 Vector2d delta = (position.subtract(ball.position));
  6.                 float r = getRadius() + ball.getRadius();
  7.                 float dist2 = delta.dot(delta);
  8.  
  9.                 if (dist2 > r*r) return; // they aren't colliding
  10.  
  11.  
  12.                 float d = delta.getLength();
  13.  
  14.                 Vector2d mtd;
  15.                 if (d != 0.0f)
  16.                 {
  17.                         mtd = delta.multiply(((getRadius() + ball.getRadius())-d)/d); // minimum translation distance to push balls apart after intersecting
  18.  
  19.                 }
  20.                 else // Special case. Balls are exactly on top of eachother.  Don't want to divide by zero.
  21.                 {
  22.                         d = ball.getRadius() + getRadius() - 1.0f;
  23.                         delta = new Vector2d(ball.getRadius() + getRadius(), 0.0f);
  24.  
  25.                         mtd = delta.multiply(((getRadius() + ball.getRadius())-d)/d);
  26.                 }
  27.  
  28.                 // resolve intersection
  29.                 float im1 = 1 / getMass(); // inverse mass quantities
  30.                 float im2 = 1 / ball.getMass();
  31.  
  32.                 // push-pull them apart
  33.                 position = position.add(mtd.multiply(im1 / (im1 + im2)));
  34.                 ball.position = ball.position.subtract(mtd.multiply(im2 / (im1 + im2)));
  35.  
  36.                 // impact speed
  37.                 Vector2d v = (this.velocity.subtract(ball.velocity));
  38.                 float vn = v.dot(mtd.normalize());
  39.  
  40.                 // sphere intersecting but moving away from each other already
  41.                 if (vn > 0.0f) return;
  42.  
  43.                 // collision impulse
  44.                 float i = (-(1.0f + Constants.restitution) * vn) / (im1 + im2);
  45.                 Vector2d impulse = mtd.multiply(i);
  46.  
  47.                 // change in momentum
  48.                 this.velocity = this.velocity.add(impulse.multiply(im1));
  49.                 ball.velocity = ball.velocity.subtract(impulse.multiply(im2));
  50.  
  51.         }