• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0

Casting a picking ray from mouse with a unique camera setup

2 posts in this topic

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  
Followers 0