为什么我尝试使 FPS 射击游戏变焦不起作用?

Why isn't my attempt at making an FPS shooter zoom working?

OBJECTIVE

我正在使用从 Unity 论坛获得的 this script 来移动我的相机。它工作完美,这正是我想要的相机风格。这是在行动:

https://streamable.com/j7ozps

我想在用户按住鼠标右键时创建缩放效果。

问题

放大后,目标偏离了很多。这是发生了什么: https://streamable.com/8aiil0

我的尝试

void Update () {
        if (Input.GetMouseButton(1))
        {
            int layerMask = 1 << CombatManager.GROUND_LAYER; // -> public const int GROUND_LAYER = 8;
            Ray mouseClick = Camera.main.ScreenPointToRay(Input.mousePosition);                         
            RaycastHit[] hitInfos;                                                                      
            float maxDistance = 100.0f;

            hitInfos = Physics.RaycastAll(mouseClick, maxDistance,
                                            layerMask, QueryTriggerInteraction.Ignore);                

            mainCamera.fieldOfView = 10;
            mainCamera.transform.LookAt(hitInfos[0].point);
        }
        else
            mainCamera.fieldOfView = startingFieldOfView;

我也试过交换 LookAt 和视野分配的顺序。

我做错了什么?

似乎你想要的是向光标位置缩放,而不是向光线击中的地方缩放,这可能不是同一个点。要检查这一点,您可以在光线照射的地方绘制一个调试立方体,以检查您正在查看的点是否是您需要的点,如下所示:

GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.position = hitInfos[0].point;

勾选 Camera.ScreenToWorldPoint 为您提供世界space 点,该点是通过将屏幕 space 点转换为距相机平面提供的距离 z 所创建的。

我会尝试什么:

Vector3 point = Camera.main.ScreenToWorldPoint(Input.mousePosition);
//check if this is the point you want to look at
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.position = point;
//look at it
mainCamera.transform.LookAt(point);

如果您在 ScreenToWorldPoint 函数中使用 cam.nearClipPlanecam.farClipPlane 应该不介意,但我会使用它以防万一某些东西没有按预期工作。

Vector3 screenPoint = Input.mousePosition;
screenPoint.z = Camera.main.farClipPlane;
Vector3 worldPoint = Camera.main.ScreenToWorldPoint(screenPoint);