In this recipe, we will create a telescopic camera that zooms in whenever the left mouse button is pressed. This can be very useful, for instance, if we have a sniper in our game.
For this recipe, we have prepared the BasicScene
Unity package, containing a scene named BasicScene
. The package is in the 1362_05_codes
folder.
To create a telescopic camera, follow these steps:
BasicScene
package into a new Project.TelescopicView
and open it in your editor.using UnityEngine; using System.Collections; using UnityStandardAssets.ImageEffects; public class TelescopicView : MonoBehaviour{ public float zoom = 2.0f; public float speedIn = 100.0f; public float speedOut = 100.0f; private float initFov; private float currFov; private float minFov; private float addFov; private VignetteAndChromaticAberration v; public float vMax = 10.0f; void Start(){ initFov = Camera.main.fieldOfView; minFov = initFov / zoom; v = this.GetComponent<VignetteAndChromaticAberration>() as VignetteAndChromaticAberration; } void Update(){ if (Input.GetKey(KeyCode.Mouse0)) ZoomView(); else ZoomOut(); float currDistance = currFov - initFov; float totalDistance = minFov - initFov; float vMultiplier = currDistance / totalDistance; float vAmount = vMax * vMultiplier; vAmount = Mathf.Clamp (vAmount,0,vMax); v.intensity = vAmount; } void ZoomView(){ currFov = Camera.main.fieldOfView; addFov = speedIn * Time.deltaTime; if (Mathf.Abs(currFov - minFov) < 0.5f) currFov = minFov; else if (currFov - addFov >= minFov) currFov -= addFov; Camera.main.fieldOfView = currFov; } void ZoomOut(){ currFov = Camera.main.fieldOfView; addFov = speedOut * Time.deltaTime; if (Mathf.Abs(currFov - initFov) < 0.5f) currFov = initFov; else if (currFov + addFov <= initFov) currFov += addFov; Camera.main.fieldOfView = currFov; } }
The zooming effect is actually caused by changes to the value of the camera's Field Of View (FOV) property; small values result in closer views of a smaller area, while high values enlarge the FOV.
The TelescopicView
script changes the camera's field of view by subtracting from it whenever the left mouse button is pressed. It also adds to the FOV value when the mouse button is not being held, until it reaches its original value.
The zoom limit of the FOV can be deduced from the code minFov = initFov / zoom;
. This means that the minimum value of the FOV is equal to its original value divided by the zoom amount. For instance, if our camera features, originally, a FOV of 60
, and we set the Telescopic View Zoom amount to 2.0
, the minimum FOV allowed will be 60/2 = 30
. The difference is shown in the following two screenshots:
3.138.106.233