# 3d balls dynamics

### Maxim Vedenyov (view profile)

Simulation of balls collisions. Balls are same. Elastic collisions. No gravity.

V=strikes_processing_2balls(r,V,dst2,trind,n1a,n2a,d2)
```function V=strikes_processing_2balls(r,V,dst2,trind,n1a,n2a,d2)

[mdst2 mi]=min(dst2(trind)); % procers only smallest distance

ind=find(dst2(trind)<=d2); % find pairs that strikes.
% trind(ind) - pair numbers
% n1a(ind) - first balls
% n2a(ind) - second balls

%if ~isempty(ind)
if mdst2<=d2
ind=mi;

% find unit vector in derection from first ball to second ball
dr=r(:,n2a(ind))-r(:,n1a(ind));

%nn=zeros(size(dr));
%nn=dr./dst(trind(ind));
nn=bsxfun(@rdivide,dr,sqrt(dst2(trind(ind))));

%vn1=(v(:,n1a(ind))'*nn)*nn;
%vn1=bsxfun(@mtimes,(v(:,n1a(ind))'*nn)
dpv1=(V(:,n1a(ind)).*nn);
dp1=sum(dpv1,1); % dot products

dpv2=(V(:,n2a(ind)).*nn);
dp2=sum(dpv2,1); % dot products

% find pairs that have balls go to each other:
ind2=find((dp1-dp2)>0);

if ~isempty(ind2)

%Vn1=bsxfun(@times,nn,dp1); % projection of first ball's velocity to normal
%Vp1=V(:,n1a(ind))-Vn1; % perpendicular component

%Vn2=bsxfun(@times,nn,dp2); % projection of first ball's velocity to normal
%Vp2=V(:,n2a(ind))-Vn2; % perpendicular component

Vn1=bsxfun(@times,nn(:,ind2),dp1(ind2)); % projection of first ball's velocity to normal
Vp1=V(:,n1a(ind(ind2)))-Vn1; % perpendicular component

Vn2=bsxfun(@times,nn(:,ind2),dp2(ind2)); % projection of first ball's velocity to normal
Vp2=V(:,n2a(ind(ind2)))-Vn2; % perpendicular component

% on normal centroid speed:
Vc=(Vn1+Vn2)/2;

% change normal speed:
Vn1s=2*Vc-Vn1;
Vn2s=2*Vc-Vn2;

V(:,n1a(ind(ind2)))=Vn1s+Vp1;
V(:,n2a(ind(ind2)))=Vn2s+Vp2;
end

end

```