# 3d vertex translated onto 2d viewport

I have a spherical world defined by simple trigonometric functions to create triangles that are relatively similar in size and shape throughout.

What I want to be able to do is use mouse input to target a range of vertices in the area around the mouse click in order to manipulate these vertices in real time.

I read a post on this forum regarding translating 3d world coordinates into the 2d viewport.. it recommended that you should multiply the world vector coordinates by the viewport and then the projection, but they didn't include any code examples, and suffice to say i couldn't get any good results.

Further information.. I am using a lookat method for the viewport. Does this cause a problem, and if so is there a solution? If this isn't the problem, does anyone have a simple code example illustrating translating one vertex in a 3d world into a 2d viewspace?

I am using XNA.

-
possible duplicate of 3d world vertex translation to go to 2d screen coords – Byte56 Nov 1 '12 at 16:15
The process you're looking for in XNA terms is "unproject" – Byte56 Nov 1 '12 at 16:24

The Viewport class has two methods that are very useful for what you want...

Viewport.Project and Viewport.UnProject,

The UnProject method converts a screen space point into a point in world space, so if you calculate two points with different Z, you can build a ray in world space or in object space if you pass the right world matrix...

Whith that ray you can calculate collisions with your triangles...

http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.viewport.unproject.aspx

``````  Vector3 pos0 = new Vector3( input.Ms1.X, input.Ms1.Y, 0 );
Vector3 pos1 = new Vector3( input.Ms1.X, input.Ms1.Y, 1 );
pos0 = device.Viewport.Unproject( pos0, camera.Projection, camera.View, World );
pos1 = device.Viewport.Unproject( pos1, camera.Projection, camera.View, World );

MouseRay = new Ray( pos0, pos1 - pos0 );
``````
-

Blau's answer says the most important stuff. Once you know how to find the ray that goes from the near plane to the far plane corresponding the exact pixel you selected, in order to do what you need, you have to check all vertices and check their distance to the ray: http://mathworld.wolfram.com/Point-LineDistance3-Dimensional.html

If the distance is smaller than a certain threshold you define, then you consider the vertex to be selected for manipulations.

-