Frame 1
function init() {
max = 10;
grav = 0.6;
bounce = -0.5;
damp = 0.98;
b = new Array();
i = 0;
while (i < max) {
attachMovie("ball", "b" + i, i);
b[i] = _root["b" + i];
b[i]._x = (Math.random() * 500) + 20;
b[i]._y = (Math.random() * 360) + 20;
b[i].vx = (Math.random() * 20) - 10;
b[i].vy = (Math.random() * 20) - 10;
b[i].m = (Math.random() * 20) + 10;
b[i]._width = (b[i]._height = b[i].m);
b[i].rad = b[i]._width / 2;
i++;
}
}
function main() {
i = 0;
while (i < b.length) {
bi = b[i];
if (bi._x < 220) {
bi.vx = bi.vx + (1 / bi.m);
} else if (bi._x > 320) {
bi.vx = bi.vx - (1 / bi.m);
} else {
bi.vy = bi.vy - ((bi._y * 0.06) / bi.m);
bi.vx = bi.vx - (((270 - bi._x) * 0.03) / bi.m);
}
bi.vy = bi.vy + grav;
bi.vx = bi.vx * damp;
bi.vy = bi.vy * damp;
bi._x = bi._x + bi.vx;
bi._y = bi._y + bi.vy;
if (bi._x > (520 - bi.rad)) {
bi._x = 520 - bi.rad;
bi.vx = bi.vx * bounce;
}
if (bi._x < (20 + bi.rad)) {
bi._x = 20 + bi.rad;
bi.vx = bi.vx * bounce;
}
if (bi._y > (370 - bi.rad)) {
bi._y = 370 - bi.rad;
bi.vy = bi.vy * bounce;
}
i++;
}
i = 0;
while (i < (b.length - 1)) {
j = i + 1;
while (j < b.length) {
checkColl(b[i], b[j]);
j++;
}
i++;
}
}
function checkColl(b1, b2) {
var dx = (b2._x - b1._x);
var dy = (b2._y - b1._y);
var dist = Math.sqrt((dx * dx) + (dy * dy));
if (dist < (b1.rad + b2.rad)) {
var angle = Math.atan2(dy, dx);
cosa = Math.cos(angle);
sina = Math.sin(angle);
vx1p = (cosa * b1.vx) + (sina * b1.vy);
vy1p = (cosa * b1.vy) - (sina * b1.vx);
vx2p = (cosa * b2.vx) + (sina * b2.vy);
vy2p = (cosa * b2.vy) - (sina * b2.vx);
P = (vx1p * b1.m) + (vx2p * b2.m);
V = vx1p - vx2p;
vx1p = (P - (b2.m * V)) / (b1.m + b2.m);
vx2p = V + vx1p;
b1.vx = (cosa * vx1p) - (sina * vy1p);
b1.vy = (cosa * vy1p) + (sina * vx1p);
b2.vx = (cosa * vx2p) - (sina * vy2p);
b2.vy = (cosa * vy2p) + (sina * vx2p);
diff = ((b1.rad + b2.rad) - dist) / 2;
cosd = cosa * diff;
sind = sina * diff;
b1._x = b1._x - cosd;
b1._y = b1._y - sind;
b2._x = b2._x + cosd;
b2._y = b2._y + sind;
}
}
init();
onEnterFrame = main;