January 12th, 2008
In 2D games, when you want to detect where mouse cursor is pointing, it’s pretty simple to calculate a target. You were drawing objects at some pixel coordinates and cursor also exists in 2D world, now just read where the mouse click has occurred.
In 3D view, mouse cursor is moving around the 2D screen space while every object is in a 3D scene. The problem here is to convert a 2D point to a 3D point and then find the object at which the cursor is pointing. Fortunately, XNA will do most of the work for us. Viewport object holds function for this purpose: Viewport.Unproject(). It’ll convert a screen 2D point to a 3D scene point.
I’ll add a new function in my xTerrain class, Intersect(), which takes two Vector3 objects. This vectors are two points in 3D scene. Function will try to find which part of the terrain lays between this two points. From MouseClick event we call Intersect function and send it two unprojected vectors. Both are unprojected from mouse coordinates X and Y but first Z component is the closest point viewport can show and second Z component is the farthest one. Intersect function will then create a ray from this two point and test if it intersects with some part of the terrain.
On pictures is the ray which is created after click in the middle of the screen.
![]() |
![]() |

