1

我已经使用 D3DXIntersect() 来选择带有十字准线的网格,但是我无法使用它来检测与地面的碰撞。我想直接射出一条射线,这样我就可以获得到低多边形网格的相应三角形的距离,但是每当调用测试时,我的 BOOL “命中”都会返回 false。

由于我不必将屏幕坐标转换为射线,因此我从射线在世界空间中的位置开始,将其转换为模型空间,然后调用 D3DXIntersect()。

....
//when I want to check collision with the mesh..
D3DXVECTOR3 origin, direction;

//divide the camera location by the scale of the mesh.
origin = D3DXVECTOR3(gCamera->pos().x / meshScale,
 gCamera->pos().y / meshScale, gCamera->pos().z / meshScale); 
direction = D3DXVECTOR3(0.0f, -10.0f, 0.0f);  //Tried -1.0 originally

//get the inverse of the mesh's world matrix
D3DXMATRIX inverseWorld;
D3DXMatrixInverse(&inverseWorld, 0, &meshWorld);

//transform the Ray using the inverse matrix
D3DXVec3TransformCoord(&origin, &origin, &inverseWorld);
D3DXVec3TransformNormal(&direction, &direction, &inverseWorld);

//Intersection Test
BOOL hit = 0;
DWORD faceIndex = -1;
float u = 0.0f;
float v = 0.0f;
float dist = 0.0f;
ID3DXBUFFER* allHits = 0;
DWORD numHits = 0;
HR(D3DXIntersect(mMesh, &origin, &direction, &hit,
&faceIndex, &u, &v, &dist, &allHits, &numHits));

if( hit )
{

   //execute code to prove this line executed...
   //change camera position
}
else
{
   //show me the test happened and there wasn't a hit
}

我最初并没有将原点除以网格比例,但是在谷歌搜索如何补偿缩放的网格之后,我发现了一个以这种方式编写的示例。如果这是一个错误,请告诉我,但即使没有在常规尺寸的网格上使用比例和测试,我仍然没有受到射线的影响。

有没有人看到任何让我无法获得成功的错误?也许我没有正确转换光线?在此先感谢您的时间。

4

1 回答 1

0

I just figured it out. Turns out it was an easy mistake. My mesh's world matrix was simply the translation matrix and not the world matrix, i.e. the translation matrix and scaling matrix multiplied together. For anyone else struggling with this technique, just make sure your matrices are correct and the above code should work.

于 2012-06-30T14:13:18.000 回答