Lord_Migit
Lord_Migit

Reputation: 51

ScreenToWorldPoint with perspective cameras

So I am having an odd problem just now. I wrote a small script that, when atatched to an object will cause it to face the mouse pointer. However, since I switched from an orthographic camera to a perspective camera, the script has ceased to work. I have added in some debug and it looks like the ScreenToWorldPoint is just returning the same value no matter where the mouse is. I suspect this has something to do with the mouse being a fundamentally 2D entity, but I am not sure how to solve the problem.

 void Update () {
     Vector3 difference = camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
     //Debug.Log(Camera.main.ScreenToWorldPoint(Input.mousePosition));
     difference.Normalize();
     difference.Set (difference.x, difference.y, 0);
 
 
     transform.up = difference;

Upvotes: 1

Views: 13556

Answers (1)

Varaquilex
Varaquilex

Reputation: 3463

This is addressed in unity answers.

Unity Answers say, and I quote:

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.

Please use google before posting a question. There is a high change that you will find your answer before posting here.

Upvotes: 6

Related Questions