I’ve been asked how to get a 3D world position from the mouse cursor’s current position on the screen. Here’s he a code snippet on how to convert a screen-space position to a world-space position:

Vector3 ScreenToWorld( Vector2 screenPos )
    // Create a ray going into the scene starting 
    // from the screen position provided 
    Ray ray = Camera.main.ScreenPointToRay( screenPos );
    RaycastHit hit;

    // ray hit an object, return intersection point
    if( Physics.Raycast( ray, out hit ) )
       return hit.point;

    // ray didn't hit any solid object, so return the 
    // intersection point between the ray and 
    // the Y=0 plane (horizontal plane)
    float t = -ray.origin.y / ray.direction.y;
    return ray.GetPoint( t );

Now you can simply pass the mouse cursor’s current position to get its equivalent world-space position like this:

Vector worldPos = ScreenToWorld( Input.mousePosition );

© 2012 Fatal Frog Software Suffusion theme by Sayontan Sinha