Accessing the Cinemachine code library, we previously created a function to turn selected cameras in an array off, allowing for changing of Virtual Cameras. But we can also manipulate just one Virtual Camera to take on multiple functions, allowing for an additional layer of depth to the existing Follow and Look At functions.
For this ‘Interactive Camera’ I want to be able to toggle through Look At targets, with one key, and also change the Field Of View values with another.
To begin, we can create a custom script on our Main Camera gameobject. Using Cinemachine and creating a variable for our Virtual Camera, as well as an array of GameObjects to track, we can get started.
This method is called in Update, and checks for Input from the ‘R’ Key. Firstly, we need to get a reference to which game object is currently being looked at.
The original challenge was to switch between two objects, which could be done with a few simple bools. But I wanted to create a more modular design, capable of an array of any size. To achieve this, we can use a for loop to cycle through the indexes of our array.
We want to check the indexes against our previously referenced current Look At target. If true, we set the target to be the next indexed object in our array. Unfortunately, when we reach the last value of our array, we end up with an error, as it won’t reset itself to 0 — we have to create that logic ourselves.
Therefore, when we find the Look At target, we can also check if the current index is the last value in our array. If this is the case, we call the TargetSwitch method with the 0 index as the target, and cancel the loop.
If this isn’t the case, the same method is called, but with the current index raised by one.
I opted for the separate method to do the switching so as not to have to set the Look At variable twice inside the for loop. Much tidier this way!
Here, we can see our two objects in the scene, as well as in the Inspector, populating the Objects To Track array.
Hitting play, then pressing the ‘R’ key, now cycles the Look At target between the objects populating the array.
To prove the modularity, we can add additional objects to ensure it’s not acting as a binary switch.
For the Field Of View change, we can follow the same principle incase someone such as a designer were to opt for less or more FOV values when playtesting. The key difference being that we’re dealing with float variables.
To access the Field Of View, we first need to access the Lens parameters.
If we wanted to change more than just the FOV, we could actually get more advanced, and set different Lens Settings as an array of structs, allowing for the toggling to also change values such as the Dutch and Clip planes.
For now, we will simply cycle between three FOV values.
Combining these two methods, we’ve created numerous different variations of one Virtual Camera using two input keys! Bringing these features into a gameplay sense could enable some very cool movement!