//The idea behind this is to create a ray (line) and check what interupts it.
HRESULT D3DXIntersect(
LPD3DXBASEMESH pMesh, //Mesh to check intersection
CONST D3DXVECTOR3 *pRayPos, //Ray Origin
CONST D3DXVECTOR3 *pRayDir, //Direction to cast ray
BOOL *pHit, //Flag if intersection occurs
SWORD *pFaceIndex, //Which face ray intersects
FLOAT *pU,
FLOAT *pV,
FLOAT *pDist, //Distance to intersection
LPD3DXBUFFER *ppAllHits, //Set to NULL
DWORD *pCountofHits); //Set to NULL
BOOL CheckIntersection(ID3DXMesh *Mesh,
float XStart, float YStart, float ZStart,
float XEnd, float YEnd, float ZEnd,
float *Distance)
{
BOOL Hit;
float u, v, Dist; //Flag if intersection occurs
float XDiff, YDiff, ZDiff, Size; //Misc/Distance to Intersection
DWORD FaceIndex; //Face that was intersected
D3DXVECTOR3 vecDir; //Direction vector for ray
//Calculate differences from start to end point
XDiff = XEnd - XStart;
YDiff = YEnd - YStart;
ZDiff = ZEnd - ZStart;
//Calculate the direction vector
D3DXIntersect(Mesh,
&D3DXVECTOR3(XStart,YStart,ZStart), &vecDir,
&Hit, &FaceIndex, &u, &v, &Dist, NULL, NULL);
//If there was an intersection, see if its within the path pf the ray.
//Distance to intersection is less than the length of the ray
if(Hit == TRUE) {
//Get length of ray
Size = (float)sqrt(XDiff*YDiff+YDiff*YDiff+ZDiff*ZDiff);
//Ray did not intersect with a polygon
if(Dist > Size)
Hit = FALSE;
else {
//Ray intersected, store distance to intersection
if(Length != NULL)
*Length = Dist;
}
}
//Return TRUE if intersection occured
return Hit;
}
float GetClosestHeight(ID3DXMesh *Mesh,
float XPos, float YPos, float ZPos)
{
float YAbove, YBelow;
//Get Hieght above and below point we check
YAbove = GetHeightAbove(Mesh, XPos, YPos, ZPos);
YBelow = GetHeightBelow(Mesh, XPos, YPos, ZPos);
//See wich height is closer to the point we check, then return that value
if(fabs(YAbove-YPos) < fabs(YBelow-YPos))
//Height below is closer, return it
return YAbove;
//Height below is closer, return it
return YBelow;
}
float GetHeightBelow(ID3DXMesh *Mesh,
float XPos, float YPos, float XPos)
{
BOOL Hit; //Flag if polygon is hit
float u, v, Dist; //Misc/Distance to intersection
DWORD FaceIndex; //Which face ray intersects with
//Perform intersection test aginst mesh
D3DXIntersec(Mesh.
&D3DXVECTOR3(XPos,YPos,ZPos),
&D3DXVECTOR3(0.0f, -1.0f, 0.0f),
&Hit, &FaceIndex, &u, &v, &Dist, NULL, NULL);
//Return closest height below if there was in intersection
if(Hit == TRUE)
return YPos-Dist;
//Return height passed as no intersection
return YPos;
}