Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public void resolveCollision(Ball ball)
- {
- // get the mtd
- Vector2d delta = (position.subtract(ball.position));
- float r = getRadius() + ball.getRadius();
- float dist2 = delta.dot(delta);
- if (dist2 > r*r) return; // they aren't colliding
- float d = delta.getLength();
- Vector2d mtd;
- if (d != 0.0f)
- {
- mtd = delta.multiply(((getRadius() + ball.getRadius())-d)/d); // minimum translation distance to push balls apart after intersecting
- }
- else // Special case. Balls are exactly on top of eachother. Don't want to divide by zero.
- {
- d = ball.getRadius() + getRadius() - 1.0f;
- delta = new Vector2d(ball.getRadius() + getRadius(), 0.0f);
- mtd = delta.multiply(((getRadius() + ball.getRadius())-d)/d);
- }
- // resolve intersection
- float im1 = 1 / getMass(); // inverse mass quantities
- float im2 = 1 / ball.getMass();
- // push-pull them apart
- position = position.add(mtd.multiply(im1 / (im1 + im2)));
- ball.position = ball.position.subtract(mtd.multiply(im2 / (im1 + im2)));
- // impact speed
- Vector2d v = (this.velocity.subtract(ball.velocity));
- float vn = v.dot(mtd.normalize());
- // sphere intersecting but moving away from each other already
- if (vn > 0.0f) return;
- // collision impulse
- float i = (-(1.0f + Constants.restitution) * vn) / (im1 + im2);
- Vector2d impulse = mtd.multiply(i);
- // change in momentum
- this.velocity = this.velocity.add(impulse.multiply(im1));
- ball.velocity = ball.velocity.subtract(impulse.multiply(im2));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement