Frame 1
function init() {
damp = 0.99;
max = 6;
grav = 2;
bounce = -0.9;
b = new Array();
i = 0;
while (i < max) {
attachMovie("ball", "b" + i, i);
var ball = ((b[i] = _root["b" + i]));
ball._x = (Math.random() * 500) + 20;
ball._y = (Math.random() * 360) + 20;
ball.m = (ball._width = (ball._height = (Math.random() * 50) + 5));
ball.radius = ball._width / 2;
ball.onPress = function () {
this.startDrag();
this.drag = true;
};
ball.onRelease = (ball.onReleaseOutside = function () {
stopDrag();
this.drag = false;
});
i++;
}
}
function main() {
i = 0;
while (i < b.length) {
var ball = b[i];
if (!ball.drag) {
ball.vx = ball.vx * damp;
ball.vy = ball.vy * damp;
ball._x = ball._x + ball.vx;
ball._y = ball._y + ball.vy;
} else {
ball.vx = ball._x - ball.oldx;
ball.vy = ball._y - ball.oldy;
ball.oldx = ball._x;
ball.oldy = ball._y;
}
if (ball._x > (520 - ball.radius)) {
ball._x = 520 - ball.radius;
ball.vx = ball.vx * bounce;
}
if (ball._x < (20 + ball.radius)) {
ball._x = 20 + ball.radius;
ball.vx = ball.vx * bounce;
}
if (ball._y > (380 - ball.radius)) {
ball._y = 380 - ball.radius;
ball.vy = ball.vy * bounce;
}
if (ball._y < (20 + ball.radius)) {
ball._y = 20 + ball.radius;
ball.vy = ball.vy * bounce;
}
i++;
}
i = 0;
while (i < (b.length - 1)) {
j = i + 1;
while (j < b.length) {
var b1 = b[i];
var b2 = b[j];
var dx = (b2._x - b1._x);
var dy = (b2._y - b1._y);
var distSQ = ((dx * dx) + (dy * dy));
var force = (((grav * b1.m) * b2.m) / distSQ);
var angle = Math.atan2(dy, dx);
b1.vx = b1.vx + ((Math.cos(angle) * force) / b1.m);
b1.vy = b1.vy + ((Math.sin(angle) * force) / b1.m);
b2.vx = b2.vx - ((Math.cos(angle) * force) / b2.m);
b2.vy = b2.vy - ((Math.sin(angle) * force) / b2.m);
var dist = Math.sqrt(distSQ);
if (dist < (b1.radius + b2.radius)) {
cosa = Math.cos(angle);
sina = Math.sin(angle);
var b1vxp = ((b1.vx * cosa) + (b1.vy * sina));
var b1vyp = ((b1.vy * cosa) - (b1.vx * sina));
var b2vxp = ((b2.vx * cosa) + (b2.vy * sina));
var b2vyp = ((b2.vy * cosa) - (b2.vx * sina));
var P = ((b1vxp * b1.m) + (b2vxp * b2.m));
var V = (b1vxp - b2vxp);
b1vxp = (P - (b2.m * V)) / (b1.m + b2.m);
b2vxp = V + b1vxp;
b1.vx = ((b1vxp * cosa) - (b1vyp * sina)) * (-bounce);
b1.vy = ((b1vyp * cosa) + (b1vxp * sina)) * (-bounce);
b2.vx = ((b2vxp * cosa) - (b2vyp * sina)) * (-bounce);
b2.vy = ((b2vyp * cosa) + (b2vxp * sina)) * (-bounce);
var diff = ((b1.radius + b2.radius) - dist);
b1._x = b1._x - ((Math.cos(angle) * diff) / 2);
b1._y = b1._y - ((Math.sin(angle) * diff) / 2);
b2._x = b2._x + ((Math.cos(angle) * diff) / 2);
b2._y = b2._y + ((Math.sin(angle) * diff) / 2);
}
j++;
}
i++;
}
}
init();
_root.onEnterFrame = main;