Search code examples
unity-game-enginecamera

How to Calculate ScreenToWorld Coefficient | Unity


I'm in need to convert Screen To World position every frame, but I can only do it on Awake/Start. Im looking for a coefficient, that I can apply every frame. Help wanted.


Solution

  • If you don't want to / can't use default unity camera's ScreenToWorldPoint method every frame/update. You can calculate coefficient on Start by this way:

    Formula: MaxRightPointOnWorld / (ScreenWidthInPixels / 2)

    Easy Implementation:

    public Vector2 GetScreenToWorldCoefficient(Camera camera)
    {
        Vector2 maxPoint = _camera.ScreenToWorldPoint(
            new Vector3(Screen.width, 0, -camera.transform.position.z)
        );
        return new Vector2(
            maxPoint.x / (Screen.width / 2)
        );
    }
    

    Note: this codepiece returns 1 coefficient, for X in my case, but at all times X and Y coefficients are same.

    Hope I helped someone. Feedback is welcome.