OK here is the code:
// Get current viewport
FD3DDevice.GetViewport(FD3DViewport);
Vec1 := D3DXVector3( X, Y, 1.0 );
Vec2 := D3DXVector3( X, Y, 2.0 );
// Get two world space coordinates that are on the same line as mouse
// and intersection point
D3DXVec3UnProject( Vec1, Vec1, FD3DViewport, matProj, matView, matIdentity );
D3DXVec3UnProject( Vec2, Vec2, FD3DViewport, matProj, matView, matIdentity );
// Use linear interpolation/extrapolation ( Result = Vec1 + s( Vec2 - Vec1 ) )
// to get the intersection point. We can calculate s because we know y-values
// of all three points and because this is LINEAR. In general, this works only
// if you know at least one component of your intersection point.
Result.x := Vec1.x + Abs(Vec1.y) / Abs(Vec1.y - Vec2.y) * (Vec2.x - Vec1.x);
Result.y := 0.0;
Result.z := Vec1.z + Abs(Vec1.y) / Abs(Vec1.y - Vec2.y) * (Vec2.z - Vec1.z);
Here Vec1 and Vec2 are just some vectors, Result is your intersection point
and X and Y are mouse screen coords. I haven''t tested it very
much though ''cos I just invented it. So go ahead and try...
The ol' 2D click -> 3D world coordinate question
And matIdentity is your world matrix. If your terrain is not
flat it will be MUCH more difficult.
flat it will be MUCH more difficult.
Yeah! I finally got it figured out! Just in case anyone want to use this later on, I''ll post the function here:
// x and y are the mouse coordinates in the client windowvoid CMyD3DApplication::GetRayFromMouse(D3DXMATRIX matProj, D3DXMATRIX matView, int x, int y){ D3DXVECTOR3 vPickRayDir,vPickRayOrig; POINT ptCursor = { x, y }; D3DXVECTOR3 v; UINT width=WIDTH, height=HEIGHT; v.x = ( ( ( 2.0f * ptCursor.x ) / m_d3dsdBackBuffer.Width ) - 1 ) / matProj._11; v.y = -( ( ( 2.0f * ptCursor.y ) / m_d3dsdBackBuffer.Height ) - 1 ) / matProj._22; v.z = 1.0f; D3DXMATRIX m; D3DXMatrixInverse( &m, NULL, &matView ); // Transform the screen space pick ray into 3D space vPickRayDir.x = v.x*m._11 + v.y*m._21 + v.z*m._31; vPickRayDir.y = v.x*m._12 + v.y*m._22 + v.z*m._32; vPickRayDir.z = v.x*m._13 + v.y*m._23 + v.z*m._33; vPickRayOrig.x = m._41; vPickRayOrig.y = m._42; vPickRayOrig.z = m._43; fT1=vPickRayOrig.y/vPickRayDir.y; fT2=vPickRayOrig.x-(vPickRayDir.x*fT1); fT3=vPickRayOrig.z-(vPickRayDir.z*fT1); lTiger1=fT2;//x-coord of the character lTiger2=fT3;//z-coord of the character //The y-coord is 0}
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement