- Home /
ScreenToWorldPoint in 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.
Any help is much appriciated! :)
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;
Try adding a z component to the required Vector3 of the ScreenToWorld function. The z position is in world units from the camera.
Answer by sniper43 · Jan 26, 2015 at 11:30 AM
Generally speaking, you don't want the transform.up to represent forward as there IS a transform.forward available.
And if you take this into account, you can simply use the LookAt function.
transform.LookAt( Camera.main.ScreenToWorldPoint( Input.mousePosition ) );
If you MUST have up as the forward direction, you can rotate along the transform.right axis by 90 degrees. As you're doing this within the function, it shouldn't jitter.
transform.Rotate( transform.right, 90f );