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.
In order to follow this recipe, please import the basicTerrain
package, available in the 0423_02_04_05
folder, into your project. The package includes a basic terrain and a camera that can be rotated via a mouse.
To create a telescopic camera, follow these steps:
02_04_05
scene.TelescopicView
and open it in your editor.using UnityEngine; using System.Collections; public class TelescopicView : MonoBehaviour{ public float ZoomLevel = 2.0f; public float ZoomInSpeed = 100.0f; public float ZoomOutSpeed = 100.0f; private float initFOV; //private Vignetting vignette; //public float vignetteAmount = 10.0f; void Start(){ initFOV = Camera.main.fieldOfView; //vignette = this.GetComponent("Vignetting") as Vignetting; } void Update(){ if (Input.GetKey(KeyCode.Mouse0)){ ZoomView(); }else{ ZoomOut(); } } void ZoomView(){ if (Mathf.Abs(Camera.main.fieldOfView - (initFOV / ZoomLevel)) < 0.5f){ Camera.main.fieldOfView = initFOV / ZoomLevel; // vignette. intensity = vignetteAmount; }else if (Camera.main.fieldOfView - (Time.deltaTime * ZoomInSpeed) >= (initFOV / ZoomLevel)){ Camera.main.fieldOfView -= (Time.deltaTime * ZoomInSpeed); // vignette. intensity = vignetteAmount * (Camera.main.fieldOfView - initFOV)/((initFOV / ZoomLevel) - initFOV); } } void ZoomOut(){ if (Mathf.Abs(Camera.main.fieldOfView - initFOV) < 0.5f){ Camera.main.fieldOfView = initFOV; // vignette. intensity = 0; }else if (Camera.main.fieldOfView + (Time.deltaTime * ZoomOutSpeed) <= initFOV){ Camera.main.fieldOfView += (Time.deltaTime * ZoomOutSpeed); //vignette.intensity = vignetteAmount * (Camera.main.fieldOfView - initFOV)/((initFOV / ZoomLevel) - initFOV); } } }
TelescopicView
script and uncomment every commented line (these are the ones referencing the vignetteAmount
variable).3.144.39.144