Tuesday, December 2, 2014

Unity: Camera ZoomIn and ZoomOut

Below is the link to a simple piece of codes which shows how to make the camera in Unity to zoom in and zoom out:

https://dl.dropboxusercontent.com/u/113201788/Unity3D/Camera.ZoomIn-ZoomOut.zip

Firstly create a C# Script named "TelescopicView" and update its codes as shown below:

using UnityEngine;
using System.Collections;

public class TelescopicView : MonoBehaviour {
 public int zoomInSpeed=100;
 public int zoomOutSpeed=100;
 public int zoomLevel=2;
 private float initFOV;

 // Use this for initialization
 void Start () {
  initFOV = Camera.main.fieldOfView;
 }
 
 // Update is called once per frame
 void Update () {
  if(Input.GetKey(KeyCode.Mouse0))
  {
   ZoomIn();
  }
  else
  {
   ZoomOut();
  }
 }

 void ZoomIn()
 {
  if(Mathf.Abs(Camera.main.fieldOfView - initFOV / zoomLevel) < 0.5f)
  {
   Camera.main.fieldOfView=initFOV / zoomLevel;
  }
  else if(Camera.main.fieldOfView-(Time.deltaTime * zoomInSpeed) >= initFOV / zoomLevel)
  {
   Camera.main.fieldOfView -= Time.deltaTime * zoomInSpeed;
  }
 }

 void ZoomOut()
 {
  if(Mathf.Abs(Camera.main.fieldOfView - initFOV) < 0.5f)
  {
   Camera.main.fieldOfView=initFOV;
  }
  else if(Camera.main.fieldOfView + (Time.deltaTime * zoomOutSpeed) <= initFOV)
  {
   Camera.main.fieldOfView += Time.deltaTime * zoomOutSpeed;
  }
 }
}

Now attach the "TelescopicView" script to the camera object in the "Hierarchy" panel (e.g., the "Main Camera"). Also with the "Main Camera" selected in the "Hierarchy" panel, select "Component->Camera Control->Camera Look" to add the Camera Look component to the "Main Camera". That's it.

The codes are self-explained, basically the techniques rely on changing the field of view of the camera by decreasing it (zoom in) or increasing it (zoom out). The zoom in happens when the user holds down the left mouse (i.e. KeyCode.Mouse0).

No comments:

Post a Comment