我想知道如何使用 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
和目标(20
或 60
)之间执行 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/