The method for the Unity camera to center and focus on objects in the scene

# Preface

In the game scene, it is often necessary to pan the camera and then focus on the object. Today I will talk about how this part is realized.

# text

# ideas

We can let the camera emit a ray from the center of the screen to the scene plane (Plane) to get the position of the current screen center in the scene, and then the difference between the target point is the distance we need to move the camera.

# Code

//聚焦对象
 private void CameraFocusAt(Transform target)
    {
        var cp = CalcScreenCenterPosOnPanel();
        var tp = target.position;
        //1.直接移动
        // mainCamera.transform.Translate(tp - cp,Space.World);
        //2.使用tween移动
        mainCamera.transform.DOMove(mainCamera.transform.position + (tp - cp), 0.5f);
    }


    /// <summary>
    /// 屏幕中心点到panel上的坐标
    /// </summary>
    /// <returns></returns>
    private Vector3 CalcScreenCenterPosOnPanel()
    {
        var ray = mainCamera.ScreenPointToRay(new Vector3((float) Screen.width / 2, (float)Screen.height / 2, 0));
        if (_plane.Raycast(ray, out var distance))
        {
            return ray.GetPoint(distance);
        }
        else
        {
            return Vector3.zero;
        }
    }

# achieve the effect

Sample code: https://github.com/dengxuhui/unity-blog-code/blob/master/UnityBlogCode/Assets/Script/EX_CameraFocus.cs

You can also download the example project, which will also put all the Unity blog code in it in the future.

Guess you like

Origin blog.csdn.net/weixin_36719607/article/details/118164849