ScreenToWorldPosition returns wrong coordinates the further i go from the centre of the screen

Hi I have a topdown 2d game with orthographic camera and this piece of code:

Vector3 mousePosition3d = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.nearClipPlane));
Debug.Log(mousePosition3d);

When I move my mouse on x axis the y value increases the further i go from point (0,0). Please see the video for more reference.

It seems like the further i go from the camera position the more at an angle the point is measured. Or is there something wrong with my setup?
I have tried providing different z value and nothing changes. I always get those small discrepancies and rotating the tank turret is inaccurate.

*i am working on a 4k monitor so I do consider this to be in editor problem but as I am not convinced.

UPDATE:
It was en error in my code! Sorry!

Thanks!

Hi @SunnyValleyStudio

You are doing screen point conversion to world point, where the position is defined by your camera near clip plane.

This will work only if your camera is aimed directly towards your xy plane, then the invisible glass plane of camera near plane will be aligned with your 2d map.

However, seems like your camera is aimed directly towards the plane…

You could also try raycasting against virtual plane object instead.

This will work even if your camera is watching the 2D map from angle, as long as the plane you define matches the plane of your 2D map:

Plane plane = new Plane(Vector3.forward, Vector3.zero);
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Vector3 pointOnPlane;
float enter;

if (plane.Raycast(ray, out enter))
{
    pointOnPlane = ray.GetPoint(enter);
    Debug.Log(pointOnPlane);
}
1 Like

Thanks for the solution. As I watch the video now it seems that it might be the mouse movement on y axis that causes to change. Maybe it’s all because higher resolution monitor.

doesn’t work for 3D

What they posted 2 years ago works perfectly fine. I’m sure for your first post you have more to say than telling someone you think something doesn’t work in 3D (in the 2D forum). :wink: