Advertisement Jump to content
Sign in to follow this  

Casting a picking ray from mouse with a unique camera setup

This topic is 1785 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi all,


I've found a lot of algos online that tell how to cast a ray directly into the screen from the mouse position.  My problem is, I am dealing with code that has a legacy camera setup, and the setup is a little bit unique.  As a result, I'm able to get the DIRECTION of the picking ray accurately, but I'm not able to get a good origin point.


Here is the code I'm using to generate the picking ray (mPMatrix and mVMatrix are stored copies of the projection and view matrix.  The world matrix is identity, I haven't even gotten that far yet).

void Game::MouseToRay(float theX, float theY)

	Matrix aProjection=mPMatrix;

	Vector aV;

	Matrix aView=mVMatrix;

	Vector aRayOrigin;
	Vector aRayDir;
	aRayDir.mX  = aV.mX*aView.mData._11 + aV.mY*aView.mData._21 + aV.mZ*aView.mData._31;
	aRayDir.mY  = aV.mX*aView.mData._12 + aV.mY*aView.mData._22 + aV.mZ*aView.mData._32;
	aRayDir.mZ  = aV.mX*aView.mData._13 + aV.mY*aView.mData._23 + aV.mZ*aView.mData._33;
	aRayOrigin.mX = aView.mData._41;
	aRayOrigin.mY = aView.mData._42;
	aRayOrigin.mZ = aView.mData._43;


This code produces a 100% accurate direction, but it produces an origin that gets less and less accurate the further the mouse is from pointing right at 0,0,0.  Aspect ratio also seems to be an issue, in that the inaccuracy seems to be different along the y axis.  I am not sure what is missing.


Now, as I said, the camera code I'm using is unorthodox, but I don't have the option to not use it.  I already had a lot of problems with the camera code and setting fog values (I had to manually add a tweak), so I expect the secret is in there.  Here is what the camera setup code for the scene looks like:

void Set3DCamera(float theCameraX, float theCameraY, float theCameraZ,
	float theLookatX, float theLookatY, float theLookatZ,
	float theUpVectorX, float theUpVectorY, float theUpVectorZ, float theFOV)
	float aWorldMatrix[4][4];
	float aViewMatrix[4][4];

	theCameraZ = -theCameraZ;
	theLookatZ = -theLookatZ;
	theUpVectorZ = -theUpVectorZ;

	// We translate the world the opposite direction of the camera (relatively speakng, of course)

	// Look-at matrix vectors
	float aLookatVectorX = theLookatX-theCameraX;
	float aLookatVectorY = theLookatY-theCameraY;
	float aLookatVectorZ = theLookatZ-theCameraZ;

	// Side vector (UP cross LOOKAT)
	float aSideVectorX = theUpVectorY * aLookatVectorZ - theUpVectorZ * aLookatVectorY;
	float aSideVectorY = theUpVectorZ * aLookatVectorX - theUpVectorX * aLookatVectorZ;
	float aSideVectorZ = theUpVectorX * aLookatVectorY - theUpVectorY * aLookatVectorX;

	// Correct the UP vector (LOOKAT cross SIDE)
	theUpVectorX = aLookatVectorY * aSideVectorZ - aLookatVectorZ * aSideVectorY;
	theUpVectorY = aLookatVectorZ * aSideVectorX - aLookatVectorX * aSideVectorZ;
	theUpVectorZ = aLookatVectorX * aSideVectorY - aLookatVectorY * aSideVectorX;

	// Normalize the lookat vector
	float len = (float)sqrt(aLookatVectorX*aLookatVectorX + aLookatVectorY*aLookatVectorY + aLookatVectorZ*aLookatVectorZ);
	aLookatVectorX /= len;
	aLookatVectorY /= len;
	aLookatVectorZ /= len;

	// Normalize side vector
	len = (float)sqrt(aSideVectorX*aSideVectorX + aSideVectorY*aSideVectorY + aSideVectorZ*aSideVectorZ);
	aSideVectorX /= len;
	aSideVectorY /= len;
	aSideVectorZ /= len;

	// Normalize the up vector
	len = (float)sqrt(theUpVectorX*theUpVectorX + theUpVectorY*theUpVectorY + theUpVectorZ*theUpVectorZ);
	theUpVectorX /= len;
	theUpVectorY /= len;
	theUpVectorZ /= len;

	// The view matrix (look-at)




	// Combine the world and view (GL doesn't support View matrices)

	// Perspective projection matrix (as per Blinn)

	float aAspect = (float)gPageWidth/(float)gPageHeight;
	float aNear = gZNear;	// This was 1.0... is it hurting anything?  I made it 0.5f so things could be closer to the camera without 
	float aFar = GetZDepth();

	float aWidth=COS(theFOV / 2.0f);
	float aHeight=COS(theFOV / 2.0f);
	if (aAspect > 1.0) aWidth /= aAspect;
	else aHeight *= aAspect;


	float s  = SIN(theFOV / 2.0f);
	float d  = 1.0f - aNear/aFar;

	float aMatrix[4][4];
	aMatrix[3][2]=-(s * aNear / d);



See that line gFogTweak near the end?  I had to add that line to make fog work correctly-- it was the exact same situation I'm dealing with here, where there were lots of answers on the web, but none of them worked correctly.  I believe that something about how that projection matrix is set up is what's throwing off my picking ray. 


I'm only middling-strong on math and I've hit a wall.  And this point all I am able to do is try random things in the hopes that one of them will work, but none of them will.  If anyone can see the problem, or what I need to add into that MouseToRay function to make this all line up, you will have my infinite gratitude, and a "special thanks" line in the credits of the game I'm working on!

Edited by Raptisoft

Share this post

Link to post
Share on other sites


I'm not where I can get to my references at the moment, so I can't check on the vector-matrix mult. However, a quick comment, if mPos[1] is supposed to be the ray direction, that doesn't look at all right. (EDIT: Up to the point, your pos and dir calcs look good.) You don't show how you use your results, but normally the direction vector should be a unit vector (i.e., normalized). Why aren't you using the direction vector you calculate, and why do you use "100"?


EDIT: You shouldn't be getting any reasonable results otherwise, but is the mouse position in client coords?

Edited by Buckeye

Share this post

Link to post
Share on other sites

Here's what I did. The code & comments describe exactly what's going on... So, you can borrow ideas from here or port it over to your unorthodox camera code:

/// <summary>
/// This takes a position in screen coordinates and converts it to a coordinate in 3D space.
/// This works by shooting a ray from the camera position to the mouse position and finding a collision point.
/// </summary>
/// <param name="Position">Screen coordinate position</param>
/// <returns>A ray you can use to intersect with</returns>
public Ray ScreenToWorld(Vector2 Position)
	//0. Convert our coordinate into NDC space coordinates (NDC = Normalized Device Coordinates. Range: X [0-1], Y [0-1] )
	Vector2 NDC = new Vector2(Position.X / m_viewport.Width, Position.Y / m_viewport.Height);

	//1. Let's pretend we're at (0,0,0) looking down (0,0,-1). We need to get our near plane corners!
	//   To do this, we'll create a fake camera to get a new view matrix. We already have our projection matrix,
	//   so, once we have both matricies, we can build a frustum at the origin looking down the Z axis.
	Matrix fakeView = Matrix.CreateLookAt(Vector3.Zero, Vector3.UnitX, Vector3.Up);
	BoundingFrustum fakeFrustum = new BoundingFrustum(fakeView * m_projection);

	//2. Now, we can grab the corners from our fake frustum and use our NDC coordinate to figure out where it should be.
	//   We know that the first four verticies are the near plane corners, starting from top left and going clockwise.
	Vector3[] fakeCorners = fakeFrustum.GetCorners();

	//get the width and height of the near and far planes from its corners, so that we can scale it by the NDC
	Vector3 nearSize = fakeCorners[2] - fakeCorners[0];
	Vector3 farSize = fakeCorners[6] - fakeCorners[4];

	Vector3 NearPt = new Vector3(fakeCorners[0].X + nearSize.X * NDC.X, fakeCorners[0].Y + nearSize.Y * NDC.Y, fakeCorners[0].Z + nearSize.Z * NDC.X);
	Vector3 FarPt = new Vector3(fakeCorners[4].X + farSize.X * NDC.X, fakeCorners[4].Y + farSize.Y * NDC.Y, fakeCorners[4].Z + farSize.Z * NDC.X);

	//3. Alright, now we've got two end points in UNTRANSFORMED 3D space on both the near plane and the far plane.
	//   In order for this to be of an use to us, we have to ROTATE and TRANSLATE our points based on our camera
	//   orientation and position, respectively.
	Vector3 finalNearPt = Vector3.Transform(NearPt, m_rotation) + m_position;
	Vector3 finalFarPt = Vector3.Transform(FarPt, m_rotation) + m_position;

	//4. We're going to need to return a ray which has a position at the near plane coordinate and points towards the
	//   far plane coordinate. That's pretty easy to do.
	Vector3 dirVec = (finalFarPt - finalNearPt);

	return new Ray(finalNearPt, dirVec);


Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using, you agree to our community Guidelines, Terms of Use, and Privacy Policy. is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!