PDA

View Full Version : Particle Collision Code issue c++



StrawberryRed
10-08-2017, 07:48 AM
Hello I am new to programming in C++ and open GL. I have written the following code for collision detection and handling code for a single particle . I see that the collision handling part is never getting executed. I have a particle and a cube. Cube is made up of 12 triangles. Whenever particle hits the cube, collision handling code be executed. But it does not happen, particle moves out of the cube under the influence of gravity. Please help in understanding why the collision handling is not happening.


void collisionDetectHandle(pba::Vector& x,pba::Vector& v,double t)
{
cout<<"COLLISIONDETECTION BEGINS HERE";
double f0,f1,intersectionTime,cr,cs,a,b;
pba::Vector velPerp,newpos,intersectionPos,e1,e2,e3,e4;

double temp_time = t;
double maxt=0;
while(NOCOLL == false)//loop until no collision
{
for( size_t i=0;i<faces.size();i++ )
{

std::vector<int>& face = faces[i];

pba::Vector p0 = Vertex(face[0]);
pba::Vector p1 = Vertex(face[1]);
pba::Vector p2 = Vertex(face[2]);

pba::Vector xP=p0;
f0=0;
f1=0;
e1=p1-p0;// e1.xyz[3]
e2=p2-p0;//e2.xyz[3]

e3= e2^e1;//cross product
e4= e1^e2;//cross product

nP= e3/(e3.magnitude());

f0=(x-xP)*nP;//dot product/inner product
f1=(x-v*temp_time-xP)*nP;
std::cout<<"f0 :"<<f0<<"\t"<<"f1:"<<f1<<"\n";
if(f0==0)continue;
else if ((f0*f1)>0)continue;
else
{

intersectionTime = ((x-xP)*nP)/(v*nP);
if (temp_time * intersectionTime <0)continue;
else if(temp_time < intersectionTime)continue;
else
{
intersectionPos = x-v*intersectionTime;
a=(e3*(e2^(intersectionPos - p0)))/(e3.magnitude()*e3.magnitude());
b=(e4*(e1^(intersectionPos - p0)))/(e4.magnitude()*e4.magnitude());


if (b<0||b>1) {cout<<"No collision occured since b<0 | b>1";return;}//no collision
if((a+b<0)||(a+b>1)) {cout<<"no collision occured since a+b <0| a+b > 1";return;}//no collision
else{

if (std::fabs(maxt)<std::fabs(intersectionTime))
{
maxt=intersectionTime;
}

cr=0.2;
cs=0.5;

velPerp = v-nP*(nP*v);//calculate V perp
reflectedVel = cs*velPerp- cr*nP*(nP*v);
newpos = intersectionPos + reflectedVel*maxt;
v= reflectedVel;
x=newpos;
}
}

}//else
}//for loop ends
//calculate maximum intersection time
temp_time= maxt;

NOCOLL = true;

}//while loop ends



}