变焦相机FOV超时

时间:2017-12-24 01:51:51

标签: 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;
        }

    }
}

我很感激任何帮助! 谢谢,圣诞快乐!

2 个答案:

答案 0 :(得分:2)

使用协同程序执行此操作。您可以使用它来启用缩放的速度或持续时间。根据是否按下或释放按键,在Mathf.Lerp与目的地cam.fieldOfView20之间执行60

注意:您必须将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;
    }
}

答案 1 :(得分:1)

获得平滑缩放动画的一种简单方法是在多个帧上执行缩放操作。因此,不要立即将fieldOfView从20更改为60,而是每帧增加fieldOfView 5,直到达到目标60.(为了延长动画,您当然可以使用比5.)因此,根据鼠标输入,您可以保持状态_zoomedIn,并根据该状态和当前fieldOfView,您可以确定是否仍需要添加或减去该值。这给你类似下面的代码:(未经测试)

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

public class zoomIN : MonoBehaviour {

    public Camera cam;
    private bool _zoomedIn = false;
    private int _zoomedInTarget = 60;
    private int _zoomedOutTarget = 20;

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

        if (Input.GetMouseButtonDown (1))
            _zoomedIn = true;

        if (Input.GetMouseButtonUp (1)) {
            _zoomedIn = false;
        }

        if (_zoomedIn) {
            if (cam.fieldOfView < _zoomedInTarget)
                cam.fieldOfView += 5;
        } else {
            if (cam.fieldOfView > _zoomedOutTarget)
                cam.fieldOfView -= 5;
        }
    }