Camera.main.ViewportToWorldPoint not working like expected.

Hello everybody,

I am writing a script that Showcases Objects that you click. For example a Sodacan on the floor will be displayed at the screen above a gui that shows some stats and a bit of text + a 3D Model of the clicked Object. Here is a bit of the code i have (without Gui stuff):

var open:boolean = true;
var close:boolean = false;

var Inst_Obj:boolean = false;

var ShowcasePos: Vector3;
var ShowcaseObj: Transform;

var GUIStyle1: GUIStyle;
var GUIStyle2: GUIStyle;
var GUIStyle3: GUIStyle;

var Player: GameObject;

var rotation: float;

function Update () {
	ShowcasePos = Camera.main.ViewportToWorldPoint (Vector3 (Screen.width/2,Screen.height/2,0));
	Player = gameObject.FindWithTag ("Player");
	var distance = Vector3.Distance(transform.position, Player.transform.position);
	if (distance < 3)
		close = true;
		close = false;
	if (close == false)
		open = false;

	if (open && Inst_Obj == false){
		ShowcaseObj = Instantiate (transform, ShowcasePos, Quaternion.identity);
		ShowcaseObj.rigidbody.useGravity = false;
		ShowcaseObj.gameObject.layer = 8;
		Inst_Obj = true;
	ShowcaseObj.position = ShowcasePos;

So it works but i have problems with positioning it (the ShowcaseObj) on the screen. So how can i use the ViewportToWorldPoint function to display it in the right Position? When I leave the Y Position on the Vector3 zero it spawns the Object right at the camera.
But when I use 1,2,3… it spawns at a completely random position very far away from the camera.
What am i doing wrong?

Thanks for the help in advance.


You have a couple of problems here. First viewport coordinates go from (0,0) in the lower left corner to (1,1) in the upper right corner. You are passing the ViewportToWorldPoint() Screen coordinates that are out of bounds of the viewport. For the center of the screen, use 0.5 for x and y, or switch to using ScreenToWorldPoint().

The second issue is see is the 0.0 for the ‘z’ value. The ‘z’ value for both ScreenToWorldPoint() and ViewportToWorldPoint() is the distance in front of the camera for the point calculation. So you want to set ‘z’ to some positive value before making the call.