- Home /
Transform's position wherever the mouse is pointing.
Ok, so I need to set the Transform position of a GameObject to the X and Z coordinates of wherever the Mouse is pointing.
I think there was a function for transforming screen coordinates (Mouse position) to World Coordinates, but I'm really unsure on how to do so.
Answer by skovacs1 · Nov 22, 2010 at 07:15 PM
There are lots of things to consider when doing this such as camera perspective distortion, etc, but the simple approach you seem to be describing would the ScreenToWorldPoint which converts a screen point to a world position on a plane parrallel to the clipping planes like this:
transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition);
but that will have a distance of 0 from the camera. You probably want something more like:
var screenPoint = Vector3(Input.mousePosition);
screenPoint.z = 10.0f; //distance of the plane from the camera
transform.position = Camera.main.ScreenToWorldPoint(screenPoint);
You should write var screenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, Input.mousePosition.z);
and not
var screenPoint = Vector3(Input.mousePosition);
Answer by Jesse Anders · Nov 22, 2010 at 11:12 PM
If the object is supposed to be constrained to the XZ plane (or any plane), another option would be to use Camera.ScreenPointToRay() to generate a picking ray, and then intersect it with the plane in question to yield the corresponding world position. (The Unity 'plane' struct has a raycast function that you can use for this.)