![](/img/trans.png)
[英]How can I get a 1 to -1 float value from the localEulerAngels of a third person camera in Unity3D?
[英]How can I get my camera to momentarily pause between different positions when using lerp in Unity3D?
我有一系列位置,我希望相機在它們之間移動/固定。 有兩個按鈕(按鈕A和按鈕B)觸發相機移動位置。 如果用戶按下按鈕A,則攝像機將束緊到陣列中的上一個位置。 如果用戶按下按鈕B,則攝像機將跳至陣列中的下一個位置。 但是,在移動到新位置之前,我希望照相機將鏡頭拉到中間位置,在那里暫停幾秒鍾,然后再移動。 這是我目前所擁有的偽代碼:
void Update()
{
if (buttonPress == a) {
positionToMoveTo = positions[currentPosition--];
}
if (buttonpress == b) {
positionToMoveTo = positions[currentPosition++];
}
}
void LateUpdate()
{
camera.lerp(intermediatePosition);
StartCoroutine(pause());
}
IEnumerator pause()
{
yield return new WaitForSeconds(3f);
camera.lerp(positionToMoveTo);
}
但是,這不起作用,因為在切換相機位置時出現奇怪的抖動,並且中間位置並不總是出現。 我認為我的問題與執行順序有關,但我無法弄清楚。 任何幫助將是巨大的:)
您可以在每幀開始新的協程,因為LateUpdate
在所有Update
調用完成后LateUpdate
運行每幀!
您可以通過稍微不同的方法來避免這種情況:
private bool isIntermediate;
private bool moveCamera;
private void LateUpdate ()
{
if(!moveCamera) return;
if(isIntermediate)
{
camera.lerp(intermediatePosition);
}
else
{
camera.lerp(positionToMoveTo);
}
}
private IEnumerator MoveCamera()
{
moveCamera = true;
isIntermediate=true;
yield return new WaitForSeconds(3f);
isIntermediate=false;
// Wait until the camera reaches the target
while(camera.transform.position == PositionToMoveTo){
yield return null;
}
// Stop moving
moveCamera = false;
// just to be sure your camera has exact the correct position in the end
camera.transform.position = PositionToMoveTo;
}
或者你可以做所有的動作在協程沒有LateUpdate
(但老實說,我不知道,如果協同程序之前或之后進行Update
)
private IEnumerator MoveCamera()
{
float timer = 3f;
while(timer>0)
{
timer -= Time.deltaTime;
camera.lerp(intermediatePosition);
yield return null;
}
// Wait until the camera reaches the target
while(camera.transform.position == PositionToMoveTo){
camera.lerp(PositionToMoveTo);
yield return null;
}
// just to be sure your camera has exact the correct position in the end
camera.transform.position = PositionToMoveTo;
}
第二個會更干凈bjt,因為我不知道是否需要在LateUpdate
運行它
注意 :Vector3的==
運算符的精度為0.00001
。 如果需要更高或更小的精度,則必須更改為
if(Vector3.Distance(camera.transform.position, PositionToMoveTo) <= YOUR_DESIRED_THRESHOLD)
現在,您要做的就是每次要更改相機位置時都呼叫協程。
void Update()
{
if (buttonPress == a)
{
// Make sure the Coroutine only is running once
StopCoroutine(MoveCamera);
positionToMoveTo = positions[currentPosition--];
StartCoroutine (MoveCamera);
}
if (buttonpress == b)
{
// Make sure the Coroutine only is running once
StopCoroutine (MoveCamera);
positionToMoveTo = positions[currentPosition++];
StartCoroutine (MoveCamera);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.