我一直试图让这件事工作2个小时,但没有运气。
BOOL Directx::Picking(HWND hWnd, AnimatedMesh *entity)
{
D3DXMATRIX matProj;
POINT pt;
D3DVIEWPORT9 vp;
D3DXMATRIX matWorld;
D3DXMATRIX matView;
GetCursorPos(&pt);
ScreenToClient(hWnd, &pt);
d3ddev->GetTransform(D3DTS_PROJECTION, &matProj);
d3ddev->GetViewport(&vp);
d3ddev->GetTransform(D3DTS_VIEW, &matView);
d3ddev->GetTransform(D3DTS_WORLD, &matWorld);
// Use inverse of matrix
D3DXVECTOR3 rayPos((float)pt.x, (float)pt.y,0); // near-plane position
D3DXVECTOR3 rayDir((float)pt.x, (float)pt.y,1); // far-plane position
D3DXVec3Unproject(&rayPos,&rayPos,&vp,&matProj,&matView,&matWorld);
D3DXVec3Unproject(&rayDir,&rayDir,&vp,&matProj,&matView,&matWorld);
rayDir -= rayPos; // make a direction from the 2 positions
D3DXVec3Normalize(&rayDir,&rayDir);
float distanceToCollision;
BOOL hasHit = 0;
if(FAILED(D3DXIntersect(entity->pDrawMesh, &rayPos, &rayDir, &hasHit, NULL, NULL, NULL, &distanceToCollision, NULL, NULL)))
{
PostQuitMessage(0);
};
if(hasHit!=0)
{
PostQuitMessage(0);
}
return hasHit;
}
我认为matWorld
的问题是因为我正在进行世界转换而不是对象转换,但这只是猜测。我发现了新的东西,我正在加载2个动画网格,第一个是立方体,第二个是平面。我对渲染它们没有任何问题,但是当我测试对立方体进行挑选时,它会说即使它没有被挑选也是如此。但对于飞机,当你点击它说它没有'
点击了。
修改
好的,所以我做了更多的调试,我得到了一些关于这个问题的结果。所以,我试着画出我的光芒!当我绘制我的光线时,我想在我点击的位置画一个点。但是当我绘制我的光线时,点接近原点(0,0,0)我再次点击而不是向下移动一点而且它一直上下移动。
以下是我绘制光线的方法
............
D3DXVec3Normalize(&rayDir,&rayDir);
Program::mesh1->FillInTransformation(0, 0, 0, 0, 0, 0, rayPos.x, rayPos.y, Program::z, true, false, false); //HERE I TOOK X AND Y OF rayPos AND DRAW DOT ON IT'S POSITION
float distanceToCollision;
BOOL hasHit = 0;
if(FAILED(D3DXIntersect(entity->pDrawMesh, &rayPos, &rayDir, &hasHit, NULL, NULL, NULL, &distanceToCollision, NULL, NULL)))
{
PostQuitMessage(0);
};
........
答案 0 :(得分:0)
试试这个:
BOOL Directx::Picking(HWND hWnd, AnimatedMesh *entity)
{
POINT pt;
D3DVIEWPORT9 vp;
D3DXMATRIX matProj, matView;
GetCursorPos(&pt);
ScreenToClient(hWnd, &pt);
float w = (float)backBufferWidth;
float h = (float)backBufferHeight;
d3ddev->GetTransform(D3DTS_VIEW, &matView);
d3ddev->GetTransform(D3DTS_PROJECTION, &matProj);
d3ddev->GetViewport(&vp);
//Transform cursor position to view space
float x = (2.0f*pt.x/w - 1.0f) / matProj(0,0);
float y = (-2.0f*pt.y/h + 1.0f) / matProj(1,1);
D3DXVECTOR3 rayOrigin(0.0f, 0.0f,0.0f); // near-plane position
D3DXVECTOR3 rayDir(x, y, 1.0f); // far-plane position
D3DXMATRIX matInvView;
D3DXMatrixInverse(&matInvView, 0, &matView);
D3DXVECTOR3 rayOriginW, rayDirW;
// Transform picking ray to world space.
D3DXVec3TransformCoord(&rayOriginW, &rayOrigin, &invView);
D3DXVec3TransformNormal(&rayDirW, &rayDdir, &invView);
D3DXVec3Normalize(&rayDirW, &rayDirW);
BOOL hasHit;
float distanceToCollision;
if(FAILED(D3DXIntersect(entity->pDrawMesh, &rayOriginW, &rayDirW, &hasHit, NULL, NULL, NULL, &distanceToCollision, NULL, NULL)))
{
PostQuitMessage(0);
};
s=rayPos;
return hasHit;
}