纳金网

标题: Unity中实现望远镜的效果 [打印本页]

作者: may    时间: 2019-7-29 23:31
标题: Unity中实现望远镜的效果

來自:hanxianseng
  1. using UnityEngine;

  2. using System.Collections;

  3. public class TelesopicView : MonoBehaviour

  4. {

  5.     public float zoomLevel = 2.0f;

  6.     public float zoomInSpeed = 100.0f;

  7.     public float zoomOutSpeed = 100.0f;

  8.     private float initFOV;

  9.     public GameObject obj;

  10.     void Start()

  11.     {

  12.         //获取当前摄像机的视野范围 unity默认值60

  13.         initFOV = Camera.main.fieldOfView;

  14.     }

  15.     void Update()

  16.     {

  17.         if (Input.GetMouseButton(0))

  18.         {

  19.             ZoomInView();

  20.             //激活ui窗口

  21.             obj.SetActive(true);

  22.         }

  23.         else

  24.         {

  25.             ZoomOutView();

  26.             //失活ui窗口

  27.             obj.SetActive(false);

  28.         }

  29.     }

  30.     //放大摄像机的视野区域

  31.     void ZoomInView()

  32.     {

  33.         if (Mathf.Abs(Camera.main.fieldOfView - (initFOV / zoomLevel)) < 0f)

  34.         {

  35.             Camera.main.fieldOfView = initFOV / zoomLevel;

  36.         }

  37.         else if (Camera.main.fieldOfView - (Time.deltaTime * zoomInSpeed) >= (initFOV / zoomLevel))

  38.         {

  39.             Camera.main.fieldOfView -= (Time.deltaTime * zoomInSpeed);

  40.         }

  41.     }

  42.     //缩小摄像机的视野区域

  43.     void ZoomOutView()

  44.     {

  45.         if (Mathf.Abs(Camera.main.fieldOfView - initFOV) < 0f)

  46.         {

  47.             Camera.main.fieldOfView = initFOV;

  48.         }

  49.         else if (Camera.main.fieldOfView + (Time.deltaTime * zoomOutSpeed) <= initFOV)

  50.         {

  51.             Camera.main.fieldOfView += (Time.deltaTime * zoomOutSpeed);

  52.         }

  53.     }

  54. }
复制代码
[backcolor=rgba(255, 255, 255, 0.8)]以上脚本挂在摄像机上,通过按下鼠标的左键可实现放大视角,松开缩小视角。为了效果更逼真可以导入Image Effects([backcolor=rgba(255, 255, 255, 0.8)]Pro[backcolor=rgba(255, 255, 255, 0.8)][backcolor=rgba(255, 255, 255, 0.8)].unitypackage[backcolor=rgba(255, 255, 255, 0.8)]资源包,为摄像机添加脚本[backcolor=rgba(255, 255, 255, 0.8)]Vignette.cs





欢迎光临 纳金网 (http://go.narkii.com/club/) Powered by Discuz! X2.5