Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question A Camera zoom-in coroutine but based on progress

Discussion in 'Scripting' started by billygamesinc, Oct 7, 2023.

  1. billygamesinc

    billygamesinc

    Joined:
    Dec 5, 2020
    Posts:
    245
    I would like to know what approaches to take in order to create a coroutine similar to a scoping in effect of a sniper.

    Goals:
    • There is a value of scope speed
    • Get the value of how close toward the target FOV is from current FOV.
    • Get the duration needed in order to reach the target FOV with the scope speed
    Mechanics:
    • The player can toggle between zoom in and zoom out at any time during zooming process
    • Zooming out goes back to default FOV and zoom in goes to a set value like 30.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,711
    Smoothing movement between any two particular values:

    https://forum.unity.com/threads/beginner-need-help-with-smoothdamp.988959/#post-6430100

    You have currentQuantity and desiredQuantity.
    - only set desiredQuantity
    - the code always moves currentQuantity towards desiredQuantity
    - read currentQuantity for the smoothed value

    Works for floats, Vectors, Colors, Quaternions, anything continuous or lerp-able.

    The code: https://gist.github.com/kurtdekker/fb3c33ec6911a1d9bfcb23e9f62adac4


    Also...

    Camera stuff is pretty tricky... you may wish to consider using Cinemachine from the Unity Package Manager.

    There's even a dedicated forum: https://forum.unity.com/forums/cinemachine.136/

    If you insist on making your own camera controller, the simplest way to do it is to think in terms of two Vector3 points in space: where the camera is LOCATED and where the camera is LOOKING.

    Code (csharp):
    1. private Vector3 WhereMyCameraIsLocated;
    2. private Vector3 WhatMyCameraIsLookingAt;
    3.  
    4. void LateUpdate()
    5. {
    6.   cam.transform.position = WhereMyCameraIsLocated;
    7.   cam.transform.LookAt( WhatMyCameraIsLookingAt);
    8. }
    Then you just need to update the above two points based on your GameObjects, no need to fiddle with rotations.