[Solved]World to Local problem

Hi,

I have a camera with an object parented to it so that the object is (or rather should) always be on screen. If i right click somewhere on screen the object should jump to where i clicked.

However with the script that i have it consistently puts the position of the object to the world position
instead of the correct localPosition.

var panel1  = GameObject.Find("Panel1");
var worldPos : Vector3 = Camera.main.ScreenToWorldPoint(Input.mousePosition);
var localPos = cam.transform.InverseTransformPoint(worldPos);
panel1.transform.localPosition = localPos;

print some of the values returns this:

Camera:(4.2, 4.0, 3.2)
worldPos(4.2, 4.0, 3.2)
localPos(0.0, 0.0, 0.0)
Panel 1 current pos(4.2, 4.0, 3.2)

Am I doing something wrong in the conversion? It keeps ending up behind the camera.

Oke solved the problem myself. Since the object was clipping other things anyway. I set up a separate UI Camera that renders everything in the UI layer on top of the viewport. Clicks received properly position the object in world space now, bsaed on the location of the UI camera.

var panel1  = GameObject.Find("Panel1");
var worldPos : Vector3 = camera.allCameras[1].ScreenToWorldPoint(Input.mousePosition);
panel1.transform.position.x = worldPos.x;
panel1.transform.position.y = worldPos.y;

There is a simpler solution. Have a look at Camera.ScreenToWorldPoint in the documentation. They set the z value, such that it is not zero. This will give the panel a distance to the camera, which is needed! Code is not tested, but at least the idea should be correct.

var panel1  = GameObject.Find("Panel1");
var mousePos : Vector3 = Input.mousePosition;
mousePos.z = 1.0; // Panel1 will be 1.0 away
var worldPos : Vector3 = Camera.main.ScreenToWorldPoint(mousePos);
var localPos = cam.transform.InverseTransformPoint(worldPos);
panel1.transform.localPosition = localPos;