- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我试图在游戏开始时让我的相机在我的场景上滚动。这是附在我的主相机上的代码
using UnityEngine;
using System.Collections;
public class cameraScript : MonoBehaviour {
public float camYLerpTime = 5000f;
float camYInitPoint = 950f;
public float camYEndPoint = 0f;
float camPosY;
//float camFieldOfViewStable = 170.5f;
// Use this for initialization
void Start () {
camIntro ();
}
// Update is called once per frame
void LateUpdate () {
if (transform.position.y!=camYEndPoint) {
transform.position = new Vector3 (transform.position.x, camPosY, transform.position.z);
}
}
void camIntro()
{
camPosY = Mathf.Lerp (camYInitPoint, camYEndPoint, camYLerpTime * Time.deltaTime);
}
}
但是,我只能在过渡完成并且相机处于最终位置时看到渲染的场景。我做错了什么?
项目设置:2D统一版本:5.1.2f1
最佳答案
问题
这里的问题是您在
中滥用了Mathf.Lerp()
void camIntro()
{
camPosY = Mathf.Lerp (camYInitPoint, camYEndPoint, camYLerpTime * Time.deltaTime);
}
您提供给 Mathf.Lerp()
的第三个参数由 camYLerpTime * Time.deltaTime
给出。这个值到底是多少?嗯,您已经设置了 camYLerpTime = 5000f
,Time.deltaTime
将在 ~0.0167 左右(假设 60 FPS,所以是 1/60)
这意味着 Mathf.Lerp()
的第三个参数将是:5000 * ~0.0167 = ~83
。所以camIntro()
的内容可以认为是:
camPosY = Mathf.Lerp (camYInitPoint, camYEndPoint, 83);
查看 documentation for Mathf.Lerp()
,第三个参数 (t
) 应介于 0-1 之间,并确定返回值与提供的开始/结束值的接近程度。 t = 0
时返回起始值,t = 1
时返回结束值。如果 t > 1
(就像在本例中,t = 83
),它被固定为 1,因此 Mathf.Lerp()
将返回结束值 (camYEndPoint
)。
这就是为什么当这段代码执行时:
void LateUpdate () {
if (transform.position.y!=camYEndPoint) {
transform.position = new Vector3 (transform.position.x, camPosY, transform.position.z);
}
}
相机立即捕捉到结束位置,因为这是 camPosY
之前从 Mathf.Lerp()
收到的值。
解决方案
那么,我们该如何解决这个问题呢?不是在调用 Start()
时调用 Mathf.Lerp()
,而是在 LateUpdate()
中调用它,并使用一个变量跟踪相机移动的进度。假设您希望运动持续 5 秒(而不是 5000 秒):
using UnityEngine;
using System.Collections;
public class cameraScript : MonoBehaviour {
public float camYLerpTime = 5f;
float camYLerpProg = 0;
float camYInitPoint = 950f;
public float camYEndPoint = 0f;
float camPosY;
//float camFieldOfViewStable = 170.5f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void LateUpdate () {
if (transform.position.y!=camYEndPoint) {
camYLerpProg += Time.deltaTime;
float camPosY = Mathf.Lerp (camYInitPoint, camYEndPoint, camYLerpProg / camYLerpTime);
transform.position = new Vector3 (transform.position.x, camPosY, transform.position.z);
}
}
}
有了这个修改后的代码,Mathf.Lerp()
的第三个参数现在由 camYLerpProg/camYLerpTime
给出,本质上是(经过的运动时间/最大运动时间) 并提供预期范围 0-1 中的值。
希望对您有所帮助!如果您有任何问题,请告诉我。
关于c# - 为什么统一相机滚动仅在过渡完成后才更新场景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32604105/
以下是我更新 tableview 单元格内的 View 高度的代码 override func layoutSubviews() { super.layoutSubviews() l
我是一名优秀的程序员,十分优秀!