我有一系列位置,我希望我的相机在它们之间移动/移动。有两个按钮(按钮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
每一帧!
您可以通过稍微不同的方法避免这种情况:
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);
}
}