image thumbnail

3d balls dynamics

by

 

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

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

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

if ~isempty(ind)

    % 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:
        Vn1=2*Vc-Vn1;
        Vn2=2*Vc-Vn2;

        V(:,n1a(ind(ind2)))=Vn1+Vp1;
        V(:,n2a(ind(ind2)))=Vn2+Vp2;
    end
    
end

Contact us