Ok, after a while, i figured out the theory about collision detection/ray tracing.
For each triangle, i set a plane normal for it and declared 3 vector points.
Then i create an object vector3d point, as well as velocity.
so this is how it goes:
Then I calculate the distance of the vector to the plane (which will be the triangle i created using p1, p2, p3)
vect3 Pos, velocity; //position and velocity of player object
vect3 IP; //intersection point;
vect3 p1, p2, p3; //3 points for the triangle
double DistRayPlane(vect3& Origin, vect3& velocity, vect3& PlaneNormal, double& D)
double cosAlpha = dot(velocity, PlaneNormal);
if(cosAlpha == 0) return -1.0; //when it is parallel, do nothing
Delta = D - (dot(Origin, PlaneNormal));
After that, here will be another function to determine if the Pos vector will be inside the triangle (p1, p2, p3) at the IP point.
So this is all set...I think. All i have to do is calculate the direction of the object, then check to see if it is inside the triangle or not when the IP hit the plane.
bool PointInTriangle(vect3& Point, vect3& v1, vect3& v2, vect3& v3)
vect3 vt1 = NormalizeVect(Point - v1);
vect3 vt2 = NormalizeVect(Point - v2);
vect3 vt3 = NormalizeVect(Point - v3);
Angle = (acos(dot(vt1, vt2))+ acos(dot(vt2, vt3)) + acos(dot(vt3, vt1)));
if(fabs(Angle - 2*PI) < EPSILON)
in the InitGL i set the value for the vectors
pl.Normal = vect3(-1, 0, 0);
Pos = vect3(0, 0, -50);
velocity = vect3(1, 0, 0);
p1 = vect3(0, 10, -45);
p2 = vect3(0, -10, -40);
p3 = vect3(0, -10, -50);
Dplane = 1;
Then, in the draw function i set up the triangle and set normal for everything i needed to.
So when the distance is bigger than 0 and the distance is still smaller than the distance the object has to travel, the Intersection point will be add in. And when the IP point is inside the triangle, collision will occurs.
glTranslatef(10, 0, 0);
glColor3f(1, 1, 1);
glNormal3f(-1, 0, 0);
glVertex3d(p1.x, p1.y, p1.z);
glVertex3d(p2.x, p2.y, p2.z);
glVertex3d(p3.x, p3.y, p3.z);
//then draw the rectangle
glTranslated(Pos.x, Pos.y, Pos.z);
glColor3f(1, 0, 0);
glVertex3f(1, 1, 0);
glVertex3f(-1, 1, 0);
glVertex3f(-1, -1, 0);
glVertex3f(1, -1, 0);
double dist = distRayPlane(Pos, velocity, pl.Normal, Dplane);
if(dist > 0)
if(dist < distRayPlane(Pos, velocity, pl.Normal, Dplane))
IP = Pos + velocity*dist;
if(VertexTriangle(IP, p1, p2, p3))
Well, the problem is it did not work. The object goes right through the triangle. Did i do something wrong or my calculation is wrong?