Zoom breaks if testing if Input.mouseScrollDelta.y != 0

Hi,
First of all, great course so far, thanks.

So I tried to add a if statement as follow to test that the scrollDelta is not 0:

 private void HandleZoom()
    {
        float scrollY = Input.mouseScrollDelta.y;
        if (scrollY != 0f)
        {
            Vector3 fromFollowOffset = cinemachineTransposer.m_FollowOffset;

            float zoomAmount = 1f;
            float zoomSpeed = 5f;

            if (scrollY > 0f)
            {
                targetFollowOffset.y -= zoomAmount;
            }
            if (scrollY < 0f)
            {
                targetFollowOffset.y += zoomAmount;
            }
            targetFollowOffset.y = Mathf.Clamp(targetFollowOffset.y, MIN_FOLLOW_Y_OFFSET, MAX_FOLLOW_Y_OFFSET);
            cinemachineTransposer.m_FollowOffset = Vector3.Lerp(fromFollowOffset, targetFollowOffset, Time.deltaTime * zoomSpeed);
        }
    }

I also tried to make the comparision with 0, 0f, 0.0f without any change…

But it break the nice smooth zoom somehow… I must be missing something.
If i remove the

        if (scrollY != 0f)

it works perfectly…

Can u help me to undestand why please?

You are using a Lerp. Lerp is used over time. When you scroll with the mouse, the Lerp is ‘set in motion’ and will zoom over time. However, the scroll only happens once. So, you are setting the Lerp in motion, but then never let it complete. Uhm. What happens is that you start the zoom. Over the next few frames, the Lerp is supposed to perform the smooth zoom, but because you are checking for 0 on each frame, and in the subsequent frames the scroll delta will be 0, you are never calling the Lerp again and it can therefore not do the rest of it’s smooth zooming

5 Likes

Thanks! I forgot that the zoom must be done even when the mouse scroll is 0. It’s clear now, thank you :wink:

If you want you can leave that ‘if’ but make sure the last line, setting the cinemachineTransposer, place that line outside the ‘if’ so it always runs.

2 Likes

Yes. Then you must also make fromFollowOffset global, or remove it altogether and reference cinemachineTransposer.m_FollowOffset directly. You will get 2 different types of zoom depending on which you choose. Making it global will give you a normal Lerp (assuming you only set it inside the ‘if’), while using it directly will give you some sort of eased, smooth Lerp that slows down the closer it gets to the target offset

3 Likes

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms