Collision detection between non-linear objects

162 Views Asked by At

I'm trying to do collision detection between two non linear objects that are moving in curve or non linear movement. how would one do that. I did it using linear movement, but I don't know the equation of two non linear objects.

double collision() // returns t>=0 the collision time or -1 if no collision
    {
    int i;
    double t,dt;
    double x,y,z,d0,d1;
    dt=_max_t;
    x=pos0[0]-pos1[0];
    y=pos0[1]-pos1[1];
    z=pos0[2]-pos1[2];
    d0=sqrt((x*x)+(y*y)+(z*z));
    x=pos0[0]-pos1[0]+(vel0[0]-vel1[0])*dt;
    y=pos0[1]-pos1[1]+(vel0[1]-vel1[1])*dt;
    z=pos0[2]-pos1[2]+(vel0[2]-vel1[2])*dt;
    d1=sqrt((x*x)+(y*y)+(z*z));
    if (d0<=_max_d) return  0.0; // collided now
    if (d0<=d1)     return -1.0; // never collide
    t=(_max_d-d0)*dt/(d1-d0);
    return t;
    }
1

There are 1 best solutions below

16
On BEST ANSWER

For each time $t$, you have the positions of the two objects $(x_{p_1}(t),y_{p_1}(t),z_{p_1}(t))$ and $(x_{p_2}(t),y_{p_2}(t),z_{p_2}(t))$

Compute the distance between the two objects as $$d(t)=\sqrt{(x_{p_1}(t)-x_{p_2}(t))^2+(y_{p_1}(t)-y_{p_2}(t))^2+(z_{p_1}(t)-z_{p_2}(t))^2}$$

Then define a collision threshold, $d_{col}$.

The collision condition is therefore, for each time $t$, $$d(t)<d_{col}.$$

That is, if the above inequality holds we have a collision at time $t$, else, we don't.

Just make sure the time interval at which you check this condition and the value of $d_{col}$ are appropriate for the problem to look realistic.

Edit: C Implementation

//assumes both p1 and p2 have the same size 
unsigned int collision(double* p1, double* p2, unsigned int size, double dcol){ 
    double d, sum=0;
    unsigned int i;

    for( i=0; i<size; i++){
        sum+=(p1[i]-p2[i])*(p1[i]-p2[i]);  
    }
    d=sqrt(sum);

    if( d<dcol ) return 1; //collision produced
    else return 0; // no collision
}

//main flow of the algorithm
int main(){

    //Initialize the position vectors p1 and p2
    double p1={0,0,0}, p2={1,1,1};
    double t=0, dt=0.01, dcol=0.01; //set dt and dcol to whatever fits you

    while(1){
         updatePositions(...); //function that updates the positions of the objects
         if(collision(p1,p2,3,dcol)==1) break;
         else {t=t+dt;}
    }
    printf("Collision produced at t=%lf\n",t);
    return 0;
}