- Home /
ScreenToWorldCoordinates not accurate
What I'm trying to do is Instantiate an object at a touch position. Here is my code:
Vector3 sp = Input.mousePosition;
Vector3 wp = Camera.main.ScreenToWorldPoint(new Vector3(sp.x,sp.y,10));
GameObject g = Instantiate(Resources.Load("Player"), wp,Quaternion.identity) as GameObject;
However is seems my wp variable is not accurate because the object spawns at the wrong location (around 15 unit left and 3 units down). I'v checked that it is not the objects fault that it is changing location, so what could it be? Any help would be appreciated.
Throw in a Debug.DrawRay(Vector3.zero, wp); and see if it points at the right spot.
Ok so I just tried it but the ray doesn't appear in my scene window or game window
Answer by daneislazy · Feb 05, 2015 at 04:51 PM
Yep, sounds about right. I was using ScreenToWorld
a while ago and was having similar issues. What is probably happening is that the Input.mousePosition
and ScreenToWorld
are not using the same coordinate rules(even though the documentation says that they do), that was my issue but I was using Event.current.mousePosition
instead. Also only my vertical/y axis was messed up. I fixed it by making a function specifically to fix the vector and using ScreenToWorldPoint(new Vector3(vIn.x, Screen.height - vIn.y))
.
I'm not sure if that will work in this case though since you seem to be having horizontal and vertical issues. Try putting in a Debug message of what the sp values are after you get them. According to the docs the lower left of the screen should be 0,0 and top right should be pixelHeight, pixelWidth.
Edit: ok just checked in my game and Input.mousePosition is working correctly. So that might not be the cause. Urm... make sure that the camera you are wanting to use is set to main camera and not something else. It might also be the depth value as that might not translate to the right point with a perspective camera, possibly aggravated if the camera is at an angle like isomentric or something... just spit balling because my initial idea was probably wrong.
I checked my coordinates and the lower left is 0,0 I also tried ScreenToWorldPoint(new Vector3(vIn.x, Screen.height - vIn.y)) but it did not work