I have been struggling with this collision detection for a while now. I have a terrain map, drawn with clockwise triangle strips. Using a formula from the book “Real Time Collision Detection” I am trying to find the height of a triangle at the current position. This is to determine the cameras height above the terrain.
I can calculate my exact position in a particular terrain chunk and retrieve the correct coordinates for the current quad but the method always returns garbage, or returns 0 for failure.
My program is fairly large so I cannot post it all, but here is the collision test function:
int LineQuad(Point p, Point q, Point a, Point b, Point c, Point d, float &r) {
Point pq, pa, pb, pc;
pq.x = q.x - p.x;
pq.y = q.y - p.y;
pq.z = q.z - p.z;
pa.x = a.x - p.x;
pa.y = a.y - p.y;
pa.z = a.z - p.z;
pb.x = b.x - p.x;
pb.y = b.y - p.y;
pb.z = b.z - p.z;
pc.x = c.x - p.x;
pc.y = c.y - p.y;
pc.z = c.z - p.z;
Point m = Cross(pc, pq);
float v = Dot(pa, m);
if (v >= 0.0f) {
printf("Triangle ABC, v=%f", v);
float u = -Dot(pb, m);
printf(", u=%f
", u);
if (u < 0.0f) { printf("Calculation Error: u=%f
", u); return 0; }
float w = -ScalarTriple(pq, pb, pa);
printf(", w=%f
", w);
if (w <= 0.0f) { printf("Calculation Error: w=%f
", w); return 0; }
float denom = 1.0f / (u + v + w);
u *= denom;
v *= denom;
w *= denom;
r = (u*a.x+u*a.y+u*a.z)+(v*b.x+v*b.y+v*b.z)+(w*c.x+w*c.y+w*c.z);
} else {
printf("Triangle ADC, v=%f", v);
Point pd;
pd.x = d.x - p.x;
pd.y = d.y - p.y;
pd.z = d.z - p.z;
float u = Dot(pd, m);
printf(", u=%f", u);
if (u < 0.0f) { printf("Calculation Error: u=%f
", u); return 0; }
float w = -ScalarTriple(pq, pa, pd);
printf(", w=%f
", w);
if (w <= 0.0f) { printf("Calculation Error: w=%f
", w); return 0; }
v = -v;
float denom = 1.0f / (u + v + w);
u *= denom;
v *= denom;
w *= denom;
r = (u*a.x+u*a.y+u*a.z)+(v*d.x+v*d.y+v*d.z)+(w*c.x+w*c.y+w*c.z);
}
return 1;
}
Point p is the current camera position.
p.x=xPos2;
p.y=gameVars.transform.yPos;
p.z=zPos2;
Point q is a vector pointing down from the camera:
q.x=xPos2;
q.y=-1;
q.z=zPos2;
Here is the output that I get from one of the quads, in the format x, y, z where y is the height value. Quad ABCD starts in the top-right corner:
a: (-10, 16, 0)
b: (-10, 16, -10)
c: (0, 16, -10)
d: (0, 16, 0)
Triangle ABC, v=1970.000000, u=-950.000000
Calculation Error, u=-950
r:0.000000
Any help would be greatly appreciated, I have been trying to figure out collision detection for a long time now.