Шарики, их скорости и координаты занес в массивы. Размеры всех шариков одинаковые.
procedure bumpWalls; //столкновение со стенами
var
i: Cardinal;
begin
with Form1 do
begin
for i := 0 to BallCount - 1 do
begin
masPosX[i] := masPosX[i] + masVelX[i];
masPosY[i] := masPosY[i] + masVelY[i];
if masPosX[i] > ClientWidth - Shp1.Width then
begin
masPosX[i] := ClientWidth - Shp1.Width;
masVelX[i] := -masVelX[i];
end
else if masPosX[i] < 0 then
begin
masPosX[i] := 0;
masVelX[i] := -masVelX[i];
end;
if masPosY[i] > ClientHeight - Shp1.Width then
begin
masPosY[i] := ClientHeight - Shp1.Width;
masVelY[i] := -masVelY[i];
end
else if masPosY[i] < 0 then
begin
masPosY[i] := 0;
masVelY[i] := -masVelY[i];
end;
end;
end;
end;
procedure bumpEachOther; //столкновение друг с другом
var
h0, h1, i, j: Cardinal;
a, b, dist, bet, x1, x2, y1, y2: extended;
n: integer;
xx0, yy0, xx1, yy1: single;
begin
for i := 1 to 10 do
begin
for h0 := 0 to ballcount - 1 do
begin
for h1 := 0 to ballcount - 1 do
if h0 <> h1 then
begin
a := MasPosX[h0] + MasVelX[h0] * 0.001 - MasPosX[h1] - MasVelX[h1] * 0.001;
b := MasPosY[h0] + MasVelY[h0] * 0.001 - MasPosY[h1] - MasVelY[h1] * 0.001;
dist := sqrt(sqr(a) + sqr(b));
if dist <= 241 then
begin
bet := arctan2(MasPosY[h1] - MasPosY[h0], MasPosX[h1] - MasPosX[h0]);
x1 := masvelx[h0] * cos(-bet) - MasVelY[h0] * sin(-bet);
y1 := MasVelX[h0] * sin(-bet) + MasVelY[h0] * cos(-bet);
x2 := MasVelX[h1] * cos(-bet) - MasVelY[h1] * sin(-bet);
y2 := MasVelX[h1] * sin(-bet) + MasVelY[h1] * cos(-bet);
MasVelX[h0] := x2 * cos(bet) - y1 * sin(bet);
MasVelY[h0] := x2 * sin(bet) + y1 * cos(bet);
masVelX[h1] := x1 * cos(bet) - y2 * sin(bet);
MasVelY[h1] := x1 * sin(bet) + y2 * cos(bet);
n := 0;
xx0 := masvelx[h0];
yy0 := masvely[h0];
xx1 := masvelx[h1];
yy1 := masvely[h1];
repeat
MasPosX[h0] := MasPosX[h0] + xx0 * 0.0011;
MasPosY[h0] := MasPosY[h0] + yy0 * 0.0011;
MasPosX[h1] := MasPosX[h1] + xx1 * 0.0011;
MasPosY[h1] := MasPosY[h1] + yy1 * 0.0011;
a := MasPosX[h0] - MasPosX[h1];
b := MasPosY[h0] - MasPosY[h1];
dist := sqrt(sqr(a) + sqr(b));
inc(n);
until (dist > 241) or (n > 50000);
end;
end;
MasPosX[h0] := MasPosX[h0] + MasVelX[h0] * 0.001;
MasPosY[h0] := MasPosY[h0] + MasVelY[h0] * 0.001;
end;
end;
end;
PosX, Posy, VelX, Vely
и так же ассоциируй их с графикой. При каждом проходе еще добавить сравнение координат м/у собой и их инверсию при условии.