Original Post
Below is some code thats is in my current project. I'm trying to project the cursor position into 3D space. The idea being i'm drawing something at the origin, and rotating it to face the cursor (or the 3D projection of it). Right now i'm drawing the object where the calculated mouse position is, thats the m_pos = -(mousePosW); line (the minus is probably bacause i've calculated it wrong). The numbers that come out don't seem to be right. Here is what i've got; Camera is set at 1000 units back from the origin ([0,0,-1000.0f]). The numbers come out right for the ray, i.e. It's direction is down the z-axis ([0.0f,0.0f,1.0f]) and the ray origin is correct ([0,0,-1000.0f] i.e. the camera). So i'm expecting 't' to be 1000, i.e. 1000 units in the ray direction, starting from the origin. Which should give me [0.0f,0.0f,0.0f]. I think i've miss understood how to use the equations. I'd really like some help, if anyone can point me in the right direction that would be great.
//Calculation for rotation.
D3DXVECTOR2 mousePos( static_cast<float>(pInput->MousePos().x), static_cast<float>(pInput->MousePos().y) );
//Mouse pos needs to be projected as a ray into 3D space as thats what the farmers position is.
//First get the proj matrix.
D3DXMATRIX proj = pCamera->Proj();
//Calculate the direction of the ray in view space
D3DXVECTOR3 dir( ((2.0f*mousePos.x/screenW - 1.0f) / proj(0,0)), ((-2.0f*mousePos.y/screenH + 1.0f) / proj(1,1)), 1.0f );
D3DXVECTOR3 origin( 0.0f, 0.0f, 0.0f );
//The ray now needs to be converted to world space, use the inverse of the view matrix
D3DXMATRIX invView;
D3DXMatrixInverse( &invView, 0, &pCamera->View() );
//Now transform it to world space.
D3DXVECTOR3 rayDir, rayOrigin;
D3DXVec3TransformCoord( &rayOrigin, &origin, &invView );
D3DXVec3TransformNormal( &rayDir, &dir, &invView );
D3DXVec3Normalize( &rayDir, &rayDir );
//Define the plane to intersect, i.e. the xy plane facing the player.
D3DXVECTOR3 planeNormal( 0.0f, 0.0f, -1.0f );
//Find the point on the ray that intersects with the plane
//We can use the equation N.O + d / N.D, but d is zero so..
float numerator = D3DXVec3Dot( &planeNormal, &rayOrigin );
float denominator = D3DXVec3Dot( &planeNormal, &rayDir );
float t = numerator / denominator;
//Now plug t into the ray equation to get the position.
D3DXVECTOR3 mousePosW = rayOrigin + (t*rayDir);
m_pos = -(mousePosW);
//Components
float xComp = mousePosW.x - m_pos.x;
float yComp = mousePosW.y - m_pos.y;
m_rotation = atan2( yComp, xComp );