假设粒子大小相对于系统尺度可以忽略不计,用点表示。检测粒子在一段直线轨迹上是否与固壁相撞。
% detectcollision.m% detect the collision between a particle and obstructions% particle moves from (x1,y1) to (x2,y2) in a line% particle is represented with a point (radius=0)% obstructions are defined in matrix 'elems', element=0: obstruction, element=1: void space% output: ifcollide, 0: no collision, 1: collisionfunction ifcollide = detectcollision(x1,y1,x2,y2,elems)ifcollide=0;% upper boundary[uby ubx]=size(elems);uby=uby-1;ubx=ubx-1;if x2<0 || x2>ubx || y2<0 || y2>uby    ifcollide=1;    returnend   % y limitsmaxy=floor(max(y2,y1));miny=floor(min(y2,y1));% moving direction in xsgndx=sign(x1-x2);if sgndx~=0    % equation of the trajectory: y=ax+c    a=(y2-y1)/(x2-x1);    c=-a*x1+y1;    if a>0        for xtrack=floor(x2):sgndx:floor(x1)      % all integer x coodinates on the track            for ytrack=max(miny,ceil(xtrack*a+c-1)):min(maxy,floor((xtrack+1)*a+c))  % all integer y coordinates of elements penetrated by the line                if elems(ytrack+1,xtrack+1)==0                    ifcollide=1;                    return                end            end        end    else        for xtrack=floor(x2):sgndx:floor(x1)            for ytrack=max(miny,ceil((xtrack+1)*a+c-1)):min(maxy,floor(xtrack*a+c))                if elems(ytrack+1,xtrack+1)==0                    ifcollide=1;                    return                end             end        end    endelse    sgndy=sign(y1-y2);    if sgndy~=0        for ytrack=floor(y2):sgndy:floor(y1)             if elems(ytrack+1,floor(x1)+1)==0                ifcollide=1;                return            end        end    endend