- for (a=1; a <= state->count; a++)
- if (a != state->mouse_ball)
- for (b=1; b <= state->count; b++)
- if (a != b)
- {
- d = ((state->px[a] - state->px[b]) *
- (state->px[a] - state->px[b]) +
- (state->py[a] - state->py[b]) *
- (state->py[a] - state->py[b]));
- dee2 = (state->r[a] + state->r[b]) *
- (state->r[a] + state->r[b]);
- if (d < dee2)
- {
- state->collision_count++;
- d = sqrt(d);
- dd = state->r[a] + state->r[b] - d;
- /* A pair of balls that have already collided in this
- * current frame (and therefore touching each other)
- * should not have another collision calculated, hence
- * the fallthru if "dd ~= 0.0".
- */
- if ((dd < -0.01) || (dd > 0.01))
- {
- cdx = (state->px[b] - state->px[a]) / d;
- cdy = (state->py[b] - state->py[a]) / d;
-
- /* Move each ball apart from the other by half the
- * 'collision' distance.
- */
- state->px[a] -= 0.5 * dd * cdx;
- state->py[a] -= 0.5 * dd * cdy;
- state->px[b] += 0.5 * dd * cdx;
- state->py[b] += 0.5 * dd * cdy;
-
- ma = state->m[a];
- mb = state->m[b];
- vxa = state->vx[a];
- vya = state->vy[a];
- vxb = state->vx[b];
- vyb = state->vy[b];
-
- vela = sqrt((vxa * vxa) + (vya * vya));
- velb = sqrt((vxb * vxb) + (vyb * vyb));
-
- vela1 = vela * ((ma - mb) / (ma + mb)) +
- velb * ((2 * mb) / (ma + mb));
- velb1 = vela * ((2 * ma) / (ma + mb)) +
- velb * ((mb - ma) / (ma + mb));
-
- vela1 *= state->e; /* "air resistance" */
- velb1 *= state->e;
+ for (a=1; a <= state->count - 1; a++)
+ for (b=a + 1; b <= state->count; b++)
+ {
+ d = ((state->px[a] - state->px[b]) *
+ (state->px[a] - state->px[b]) +
+ (state->py[a] - state->py[b]) *
+ (state->py[a] - state->py[b]));
+ dee2 = (state->r[a] + state->r[b]) *
+ (state->r[a] + state->r[b]);
+ if (d < dee2)
+ {
+ state->collision_count++;
+ d = sqrt(d);
+ dd = state->r[a] + state->r[b] - d;
+
+ cdx = (state->px[b] - state->px[a]) / d;
+ cdy = (state->py[b] - state->py[a]) / d;
+
+ /* Move each ball apart from the other by half the
+ * 'collision' distance.
+ */
+ state->px[a] -= 0.5 * dd * cdx;
+ state->py[a] -= 0.5 * dd * cdy;
+ state->px[b] += 0.5 * dd * cdx;
+ state->py[b] += 0.5 * dd * cdy;
+
+ ma = state->m[a];
+ mb = state->m[b];
+
+ vxa = state->vx[a];
+ vya = state->vy[a];
+ vxb = state->vx[b];
+ vyb = state->vy[b];
+
+ vca = vxa * cdx + vya * cdy; /* the component of each velocity */
+ vcb = vxb * cdx + vyb * cdy; /* along the axis of the collision */
+
+ /* elastic collison */
+ dva = (vca * (ma - mb) + vcb * 2 * mb) / (ma + mb) - vca;
+ dvb = (vcb * (mb - ma) + vca * 2 * ma) / (ma + mb) - vcb;
+
+ dva *= state->e; /* some energy lost to inelasticity */
+ dvb *= state->e;
+