c# - 变焦相机 FOV 超时

标签 c# unity3d

我想知道如何使用 c# 在 Unity3d 中平滑地放大和平滑地按下按钮。我已经缩小了部分,但不确定如何平滑地进行放大和缩小的过渡。例如,我希望它像在 ARMA 或 DayZ 游戏中一样平滑地放大。

这是我的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class zoomIN : MonoBehaviour {

    public Camera cam;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

        if (Input.GetMouseButton (1)) {
            cam.fieldOfView = 20;
        }

        if (Input.GetMouseButtonUp (1)) {
            cam.fieldOfView = 60;
        }

    }
}

如果有任何帮助,我将不胜感激! 谢谢,圣诞快乐!

最佳答案

使用协程来做到这一点。您可以使用它来启用缩放的速度或持续时间。根据 key 是否在 cam.fieldOfView 和目标(2060)之间执行 Mathf.Lerp被按下或释放。

注意:您必须将 Input.GetMouseButton 更改为 Input.GetMouseButtonDown 否则您的第一个 if 语句将在每一帧运行,而鼠标右键按钮被按住。我想你只想一次是真的。

public Camera cam;
Coroutine zoomCoroutine;

// Update is called once per frame
void Update()
{
    if (Input.GetMouseButtonDown(1))
    {
        //Stop old coroutine
        if (zoomCoroutine != null)
            StopCoroutine(zoomCoroutine);

        //Start new coroutine and zoom within 1 second
        zoomCoroutine = StartCoroutine(lerpFieldOfView(cam, 20, 1f));
    }

    if (Input.GetMouseButtonUp(1))
    {
        //Stop old coroutine
        if (zoomCoroutine != null)
            StopCoroutine(zoomCoroutine);

        //Start new coroutine and zoom within 1 second
        zoomCoroutine = StartCoroutine(lerpFieldOfView(cam, 60, 1f));
    }

}


IEnumerator lerpFieldOfView(Camera targetCamera, float toFOV, float duration)
{
    float counter = 0;

    float fromFOV = targetCamera.fieldOfView;

    while (counter < duration)
    {
        counter += Time.deltaTime;

        float fOVTime = counter / duration;
        Debug.Log(fOVTime);

        //Change FOV
        targetCamera.fieldOfView = Mathf.Lerp(fromFOV, toFOV, fOVTime);
        //Wait for a frame
        yield return null;
    }
}

关于c# - 变焦相机 FOV 超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47957484/

相关文章:

c# - 如何将 MonoBehaviour 添加到 sprite (Player)?

c# - 即使调用更改时 bool 仍然为 false

unity3d - 获取 Sprite 的宽度

c# - 如何从 jQuery AJAX 调用向 UI 反馈代码隐藏进程的当前进度

c# - FFmpeg (sharpFFmpeg) 解码 - protected 内存错误

c# - Unity3D,C#如何保存对象的位置并稍后重新启动它们?

c# - 在 Unity 中构建和加载 Assetbundle

c# - 如何将 session 数据从 Controller 传递到 View (MVC)

C# 使用参数和扩展方法

c# - 将 razor (cshtml) 和 c# 项目添加到 Visual Studio vb 网站是否错误?