- Home /
2d mouseposition in a 3d world
I'm attempting to make a game where the player draws on a plane, but position the pen is giving me problems.
I've tried-
Vector3 clickedposition2 = Input.mousePosition; and the pen just flew all over the screen and in and out of my view. When I tried: Vector3 clickedposition = Camera.main.ScreenToWorldPoint(Input.mousePosition); The pen just stayed stationary. For both I changed the pen's position with: a.rigidbody.position = new Vector3(clickedposition.x, 10, clickedposition.y);
Basically, I'm just trying to get the pen to follow my mouse as it goes left/right-x direction and forward/backward-as mouse goes to top of the screen and to the bottom of the screen. Any advice?
Answer by TheDarkVoid · May 10, 2014 at 05:13 PM
Most of the time when you're doing something regarding screen position (0,0) is the top left of the screen, mousePosition gives you the mouse's position with (0,0) being bottom left of the screen. So you need to convert the y property by subtracting from Screen.Height.
It would look something like this:
Vector3 rawPos = Input.mousePosition;
Vector3 clickedposition2 = new Vector3(rawPos.x, Screen.height - rawPos.y, 0);
Input.mousePosition uses screen space. If you're using GUI space, then you must be using OnGUI code, in which case just use Event.current.mousePosition ins$$anonymous$$d. No need to convert anything.
However none of this actually has anything to do with the question.
Answer by Eric5h5 · May 10, 2014 at 05:18 PM
Camera.main.ScreenToWorldPoint(Input.mousePosition)
is mostly correct, but you need to supply a Z value, since otherwise it's using 0, which is at the camera (hence the "stayed stationary" thing).
Answer by Jeff-Kesselman · May 10, 2014 at 06:28 PM
If you want a point that is at N units in from the screen, and appears at mouse position x,y you can use
Ray mouseray = Camera.main.ScreenToRay(Input.mousePosition);
Vector3 point = Ray.GetPoint(<distance N>);
If you want where that pixel point is on an arbitrary surface in the 3D space, then do a ray cast with that ray against the surface in question.
I tried that and got errors. It says there's no such thing as ScreenToRay. Did you mean ScreenPointToArray. Also, for GetPoint it says that an object reference is required to access non-static member-UnityEngine.ray.getpoint(float)
Your answer
Follow this Question
Related Questions
Isometric camera 2d or 3d 2 Answers
Close meshes render in 2D, but not 3D 0 Answers
Switching Between "Dimensions"? 1 Answer
How to make quad's always face player? 2 Answers