Camera Zoom

So I just started the RPG course and I got sidetracked on a tangent trying to get my camera to zoom in and out. Most of what I found on the web was using field of view but that kept distorting the view. Eventually cobbled this together. It works pretty good for my purposes. I thought I would share in case anybody else is having issues with camera zoom.

    void ZoomCamera()
        float scrollChange = Input.GetAxis("Mouse ScrollWheel");

        if (!Mathf.Approximately(scrollChange, 0f))
            scrollChange *= -1f;

            // in order for the direction to be correct, have to subtract the origin point from the destination point
            Ray cameraArmRay = new Ray(player.transform.position, Camera.main.transform.position - player.transform.position);

            float scrollSpeedDistanceFactor = Mathf.Abs(Vector3.Distance(Camera.main.transform.position, player.transform.position));

            float distance = scrollChange * zoomSpeed + scrollSpeedDistanceFactor;

            Vector3 newPos = cameraArmRay.GetPoint(distance);

            if(Vector3.Distance(newPos,player.transform.position) >= maxCameraDistance)
                newPos = cameraArmRay.GetPoint(maxCameraDistance);
            if(Vector3.Distance(newPos,player.transform.position) <= minCameraDistance)
                newPos = cameraArmRay.GetPoint(minCameraDistance);

            Camera.main.transform.position = newPos;

Edit: slight update to the ray, need to subtract original position from the target position for the direction to be correct

Edit: Updated to add clamping for min and max zoom.

1 Like

Privacy & Terms