根据点坐标改变字体显示位置

  stackoverflow找到的方法:http://stackoverflow.com/questions/11714298/d3dxvec3project-requiring-half-the-object-position/11762956#11762956

  昨天试了好几种方法,都无效,也许是我笨吧。。。

  简单的来说,根据世界坐标系中点的位置利用D3DXVec3Project函数,找到屏幕中该点的投影位置,然后在该位置绘制字体。

  

 1 D3DXVECTOR3 CMFC_D3DView::ToScreenSpace(D3DXVECTOR3 position) 
 2 {   
 3     D3DXVECTOR3 out;
 4     D3DVIEWPORT9 view;
 5     D3DXMATRIX matView;
 6     D3DXMATRIX matWorld;
 7     D3DXMATRIX matProj;
 8     D3DXMATRIX worldPos;
 9     D3DXMATRIX worldRotX;
10     D3DXMATRIX worldRotY;
11     D3DXMATRIX worldRotZ;
12     D3DXMATRIX worldScl;
13 
14     _device->GetViewport(&view); //view in debug is showing all the correct values.
15     _device->GetTransform(D3DTS_VIEW, &matView); //view is set each frame from the camera
16     _device->GetTransform(D3DTS_PROJECTION, &matProj); //this is set once in the scene manager
17     D3DXMatrixIdentity(&matWorld);
18     //D3DXMatrixTranslation(&matWorld, position.x, position.y, position.z); //uses the given position for the world matrix
19 
20     D3DXVec3Project(&out, &position, &view, &matProj, &matView, &matWorld);
21 
22     return out;
23 }

  stacoverflow中题主出现的问题是显示字体的位置和预想中的不一样,原因就是他改变了世界矩阵matWorld,因为D3DVec3Project函数第二个参数就已经指定点的位置了,所以输入的世界坐标矩阵应该为单位矩阵才不会出现error,所以我就将matWorld单位化了一下,然后在画点的循环中添加

  

1         D3DXVECTOR3 pOut;
2         D3DXVECTOR3 pIn = D3DXVECTOR3(m_pointList[i].x,m_pointList[i].y,m_pointList[i].z);
3         pOut = ToScreenSpace(pIn);
4         SetRect( &rc, pOut.x,pOut.y, pOut.x+150,pOut.y+100 );
5         m_pFont->DrawTextA(0, "Hello World", -1, &rc, 0, WHITE);

  完整的代码是这样的

  

 1 void CMFC_D3DView::DrawPointUsingSphere()
 2 {
 3     
 4     _device->BeginScene();
 5     for (int i = 0;i<m_pointList.size();i++)
 6     {
 7         _device->SetMaterial(&RED_MTRL);
 8         _device->SetTransform(D3DTS_WORLD,&m_MatrixOfPoint[i]);
 9         m_ObjectOfPoint[i]->DrawSubset(0);//画球(我是用球代替的点)
10         
11 
12         D3DXVECTOR3 pOut;
13         D3DXVECTOR3 pIn = D3DXVECTOR3(m_pointList[i].x,m_pointList[i].y,m_pointList[i].z);
14         pOut = ToScreenSpace(pIn);
15         SetRect( &rc, pOut.x,pOut.y, pOut.x+150,pOut.y+100 );
16         m_pFont->DrawTextA(0, "Hello World", -1, &rc, 0, WHITE);//显示文本
17 
18 
19         
20         
21     }
22     _device->EndScene();
23 
24     
25 }

  

  

原文地址:https://www.cnblogs.com/AZ-ZK/p/4235796.html