- Home /
ScreenToWorldPoint() not working
Hi,
I'm currently experimenting with ScreenToWorldPoint(), and something just doesn't seem to be working right...
Whenever I use this code:
function Update() {
Debug.Log(camera.ScreenToWorldPoint(Input.mousePosition));
}
It just shows (0.0 ,125.0, 0.0) all the time in the Debug console, regardless of how much I move the cursor around the screen.
How can I make my code display the actual world coordinates my mouse is currently passing over?
Thanks in advance. :)
Answer by aldonaletto · Oct 12, 2012 at 09:03 PM
ScreenToWorldPoint receives a Vector3 argument where x and y are the screen coordinates, and z is the distance from the camera. Since Input.mousePosition.z is always 0, what you're getting is the camera position.
The mouse position in the 2D screen corresponds to a line in the 3D world passing through the camera center and the mouse pointer, thus you must somehow select which point in this line you're interested in - that's why you must pass the distance from the camera in z.
If you try something like this:
function Update() {
var mousePos = Input.mousePosition;
mousePos.z = 10; // select distance = 10 units from the camera
Debug.Log(camera.ScreenToWorldPoint(mousePos));
}
you will get the world point at 10 units from the camera.
Hey it still does not work for me :(
BoxCollider2D destroyBox = Camera.main.GetComponent<BoxCollider2D>();
colliderPos = camera.ScreenToWorldPoint(new Vector3(0, 0, -10));
Vector2 posXY = new Vector2(colliderPos.x,colliderPos.y);
destroyBox.center = posXY;
I want the BoxCollider2D to be on the left side of the Camera, all it does is positioning it about 1 unit left from the center of the camera... anyone an idea?
Almost. But it works only when player is standing in place. I'm moving camera with player, and then it does not work. This is not the true position of the mouse in the map. Only relative to center.
Thank you, @aldonaletto! I'm newbie. Your answer is the only one that make me understand how to use ScreenToWorldPoint. I don't understand until see your answer. I don't know where to like or give you 1point I'm having.
Answer by Eric5h5 · Oct 12, 2012 at 08:52 PM
You have to specify a Z position, like the code example in the docs does.
Your answer
Follow this Question
Related Questions
Camera Screen to world point returns cameras transform position. 8 Answers
Unity Look at Mouse Position 2D C# 3 Answers
Trying To Find Mouse Position On Tap 1 Answer
Converting Input.mousePosition to world coordinates 1 Answer
Find TextureCoordinates from plane with out raycast only using mouse position on plan 0 Answers