Search code examples
c#unity-game-enginegame-developmentunity3d-editor

Moving camera FOV between a min and max value


I need a code that move camera field of view (FOV) between a min and max value like 50-70 to zoom in and zoom out the camera view

For that i tried Mathf.MoveTowards function and it works well : GetComponent<Camera>().fieldOfView = Mathf.MoveTowards(camFOV,maxFOV,speed*Time.deltaTime)

Now i need this to run like that : 1)First wait 2 to 5 seconds 2)Zoom in (decrease fov to minFOV) 3)Wait 1 to 3 seconds randomly 4)Zoom out (increase fov to maxFOV) 5)REAPET THIS PROCESS UNTIL GAME RUNS

Please help me! Thanks.


Solution

  • This type of "do X, wait, do Y, wait" problem is a great use for Coroutines. In your specific case, it would look something like:

    IEnumerator ChangeCameraFOV(Camera camera) {
      while (true) { // Or until some condition
    
        // Wait 2-5 seconds (random)
        yield return new WaitForSeconds(Random.Range(2f, 5f));
    
        // Zoom in
        while (camera.fieldOfView > minFOV) {
          camera.fieldOfView = Mathf.MoveTowards(camera.fieldOfView, minFOV, speed * Time.deltaTime);
          yield return null; // Wait for next frame
        }
        
        // Wait 1-3 seconds (random)
        yield return new WaitForSeconds(Random.Range(1f, 3f));
    
    
        // Zoom out
        while (camera.fieldOfView < maxFOV) {
          camera.fieldOfView = Mathf.MoveTowards(camera.fieldOfView, maxFOV, speed * Time.deltaTime);
          yield return null; // Wait for next frame
        }
      }
    }
    

    And then start the coroutine with StartCoroutine:

    Corotuine cameraChangeCoroutine;
    public void Start() {
      cameraChangeCoroutine = StartCoroutine(ChangeCameraFOV(GetComponent<Camera>()));
    }
    

    And stop it with StopCoroutine:

    StopCoroutine(cameraChangeCoroutine);