- Home /
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;
else
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.
-Alexander
Answer by robertbu · Jul 30, 2014 at 05:39 PM
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.
Thank you. I switched to ScreenToWorldPoint and it works perfectly. I know I´m supposed to make a new question but really quick: How can I render the Object infront of the GUI? I´m using a different camera with a higher depth but it still is below the GUI.
I don't know the answer, but a quick search gives me an answer by someone I trust:
http://answers.unity3d.com/questions/30230/rendering-a-camera-in-front-of-a-gui-element.html
Your answer
Follow this Question
Related Questions
Problems with ScreenToWorldPoint in 2D game 1 Answer
Viewport to World Coordinates 2 Answers
mouse Input Instantiate 0 Answers
Instantiate Game object at clicked position? 3 Answers
How to activate a button? 1 Answer