鼠标选取3D物体的问题 - 为什么选不到?
jxc 2005-04-11 07:26:50 下面是某个例子的代码,为什么实际选取不到呢?
我用的是VC6 , DX8.1
long cApp::GetCharacterAt(long XPos, long YPos)
{
D3DXVECTOR3 vecRay, vecDir;
D3DXVECTOR3 vecMeshRay, vecMeshDir;
D3DXVECTOR3 vecTemp;
D3DXMATRIX matProj, matView, *matWorld;
D3DXMATRIX matInv;
DWORD FaceIndex;
BOOL Hit;
float u, v, Dist;
sCharacter *CharPtr;
sMesh *MeshPtr;
// Get parent character object
if((CharPtr = m_CharController.GetParentCharacter()) == NULL)
return -1;
// Get the project, view, and inversed view matrices
m_Graphics.GetDeviceCOM()->GetTransform(D3DTS_PROJECTION, \
&matProj);
// Compute the vector of the pick ray in screen space
vecTemp.x = (((2.0f * (float)XPos) / \
(float)m_Graphics.GetWidth()) - 1.0f) / \
matProj._11;
vecTemp.y = -(((2.0f * (float)YPos) / \
(float)m_Graphics.GetHeight()) - 1.0f) / \
matProj._22;
vecTemp.z = 1.0f;
m_Graphics.GetDeviceCOM()->GetTransform(D3DTS_VIEW, \
&matView);
D3DXMatrixInverse(&matInv, NULL, &matView);
// Transform the screen space ray
vecRay.x = matInv._41;
vecRay.y = matInv._42;
vecRay.z = matInv._43;
vecDir.x = vecTemp.x * matInv._11 + \
vecTemp.y * matInv._21 + \
vecTemp.z * matInv._31;
vecDir.y = vecTemp.x * matInv._12 + \
vecTemp.y * matInv._22 + \
vecTemp.z * matInv._32;
vecDir.z = vecTemp.x * matInv._13 + \
vecTemp.y * matInv._23 + \
vecTemp.z * matInv._33;
// Scan through each character and intersect check
while(CharPtr != NULL) {
// Scan through character meshes
MeshPtr = CharPtr->Object.GetMesh()->GetParentMesh();
while(MeshPtr != NULL) {
// Transform ray and direction by object's
// world transformation matrix
matWorld = CharPtr->Object.GetMatrix();
D3DXMatrixInverse(&matInv, NULL, matWorld);
D3DXVec3TransformCoord(&vecMeshRay, &vecRay, &matInv);
D3DXVec3TransformNormal(&vecMeshDir, &vecDir, &matInv);
// Check for intersection
D3DXIntersect(MeshPtr->m_Mesh, &vecMeshRay,&vecMeshDir, \
&Hit, &FaceIndex, &u, &v, &Dist,NULL,NULL);
// Check if ray hit character and return ID if so
if(Hit == TRUE)
return CharPtr->ID;
// Go to next mesh
MeshPtr = MeshPtr->m_Next;
}
// Go to next character
CharPtr = CharPtr->Next;
}
return -1; // Return no hit
}