Unity實現瞄準鏡效果

本文實例為大傢分享瞭Unity實現瞄準鏡效果的具體代碼,供大傢參考,具體內容如下

using UnityEngine;
using System.Collections;
 
public class TelesopicView : MonoBehaviour
{
 
    public float zoomLevel = 2.0f;
    public float zoomInSpeed = 100.0f;
    public float zoomOutSpeed = 100.0f;
 
    private float initFOV;
    public GameObject obj;
    void Start()
    {
        //獲取當前攝像機的視野范圍 unity默認值60
        initFOV = Camera.main.fieldOfView;
    }
 
    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            ZoomInView();
            //激活ui窗口
            obj.SetActive(true);
        }
        else
        {
            ZoomOutView();
            //失活ui窗口
            obj.SetActive(false);
        }
    }
 
    //放大攝像機的視野區域
    void ZoomInView()
    {
        if (Mathf.Abs(Camera.main.fieldOfView - (initFOV / zoomLevel)) < 0f)
        {
            Camera.main.fieldOfView = initFOV / zoomLevel;
        }
        else if (Camera.main.fieldOfView - (Time.deltaTime * zoomInSpeed) >= (initFOV / zoomLevel))
        {
            Camera.main.fieldOfView -= (Time.deltaTime * zoomInSpeed);
        }
    }
 
    //縮小攝像機的視野區域
    void ZoomOutView()
    {
        if (Mathf.Abs(Camera.main.fieldOfView - initFOV) < 0f)
        {
            Camera.main.fieldOfView = initFOV;
        }
        else if (Camera.main.fieldOfView + (Time.deltaTime * zoomOutSpeed) <= initFOV)
        {
            Camera.main.fieldOfView += (Time.deltaTime * zoomOutSpeed);
        }
    }
}

此腳本掛到unity主相機即可,可通過更改zoomLevel更改倍鏡倍數

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。