Marble machine making of 4

Collision

For detecting a collision of a marble with an other Object (the yellow box) I use the trace command. By creating (green) Vectors from the middle of the sphere, I must trace all vectors and find the collision point (or not). If this point is inside the sphere, I add the part of the red Vector which is inside the yellow box to the speed vector of the marble.
In the real scene I use 10 times more collision vectors than in this demo.

#macro collision (pos,s,sp,rot,rot_inc obj)      
    #declare xi=0;
    #while (xi<360)      
        #declare yi=0;
        #while (yi<180)                 
            #declare Hit_Normal = <0,0,0>;
            #declare ve = <0,0,1>;
            #declare ve =vrotate (ve, <xi,yi,0>);
            #declare treffer = trace (obj,pos,ve,Hit_Normal);
            #if (vlength( Hit_Normal) !=0)
                #if( vlength(pos - treffer)< s)
                    #declare pos= pos + Hit_Normal*(s-vlength(pos - treffer));
                    #declare sp = sp  + Hit_Normal*((s*1.016)-vlength(pos - treffer));  
                #end#end#declare yi = yi +60.0;
        #end
     #end
#end